栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Express + Nginx。无法提供静态文件

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Express + Nginx。无法提供静态文件

您无需配置Nginx Express即可提供静态文件。两者都有能力独立完成这项工作,但这取决于您选择。

对于这些示例,我假设您的问题中提供的文件结构相同。

在这两种配置中,都从/加载HTML文件:

<script src="/main.js"></script> <!-- loads from myapp/public/main.js -->

Express作为静态文件服务器,Nginx作为反向代理

快递应用

const express = require('express');const app = express();app.use(express.static('public')); // notice the absence of `__dirname`, explained later on// if the request URL doesn't match anything in the 'public' folder,// it will start searching here next.app.use(express.static('some_other_folder'));// from my testing, express will automatically locate index.html if// it is in a static folder. Declaring a route is not required.app.listen(8080);// GET / => index.html// GET /main.js => main.js

快速提示 :不需要使用

__dirname
in
express.static()
。引擎盖下(实际上,这是在这里第65行),快速使用本机的Node.js path.resolve()

。从文档:

path.resolve()方法将一系列路径或路径段解析为绝对路径。

使用

path.resolve(__dirname, 'public')
实际上会 返回与相同
的结果
path.resolve('public')
。我认为您的问题确实是在告诉Nginx提供静态文件并将相同的请求代理到Express。好,接下来我的答案。

Nginx配置

server {  listen 8081; # must be different port from Express  server_name example.com;  location / {    # hand ALL requests back to express    proxy_pass http://localhost:8080;   }}

Nginx作为静态文件服务器,Express作为API服务器

Nginx配置

server {  listen 8081;  server_name example.com;  location / {    root /path/to/website/public;    index index.html;    try_files $uri $uri/ @express; # instead of 404, proxy back to express using a named location block;    # source: https://stackoverflow.com/a/15467555/8436941  }  location @express {    proxy_pass http://localhost:8080;  }}

快递应用

const express = require('express');const app = express();// actually, Nginx has already taken care of static files. You can still define other routes for API functions for example.app.get('/my/api', (req, res) => {});app.listen(8080);

希望这可以帮助!



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/448615.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号