路由在我的本地计算机上按预期运行。但不提供/public 或/api 路由。
我已经为 node.mydomain.com 设置了一个服务器 block ,安装了一个 Node 应用程序,并且对于 Express 应该提供的所有路由(静态和 API)都收到 404 错误。
node.mydomain.com =>/public/index.html(工作正常)
node.mydomain.com/style.css =>/public/style.css(404 错误)
node.mydomain.com/api/puppies =>/api(404 错误)
这个应用程序应该在我的子域 (node.mydomain.com) 的根目录中运行,它实际上是 localhost:3000。我做错了什么?
NGINX 服务器 block
#server {
listen 80;
listen [::]:80;
root /var/www/node.mydomain.com/html;
# Add index.php to the list if you are using PHP
index index.php index.html index.htm index.nginx-debian.html;
server_name node.mydomain.com www.node.mydomain.com;
location / {
# First attempt to serve request as file, then
# as directory, then fall back to displaying a 404.
try_files $uri $uri/ =404;
# node app hello.js
proxy_pass http://localhost:3000;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_buffering off;
}
location /app2 {
proxy_pass http://localhost:3000;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_buffering off;
}
}
特快路线
const express = require('express');
const app = express();
const path = require('path');
app.use(express.static(path.join(__dirname, '../public')));
app.use('/bootstrap', express.static(path.join(__dirname, '..', '/node_modules/bootstrap/dist')));
app.use('/api', require('./api'));
// handle 404s
app.get('*', function (req, res) {
res.sendFile(path.join(__dirname, '../public/index.html'));
});
// handle 500s
app.use(function (err, req, res, next) {
console.error(err);
console.error(err.stack);
res.status(err.status || 500).send(err.message || 'Internal server error.');
});
const port = process.env.PORT || 3000;
app.listen(port, function () {
console.log(`Your server, listening on port ${port}`);
console.log(`Browse to http://localhost:${port} to view your app`);
});
API 路由
//api root
router.get('/', function (req, res, next) {
res.send('api root');
});
// /api/campuses
router.get('/campuses', function (req, res, next) {
Campuses.findAll({})
.then(campuses => res.json(campuses))
.catch(next);
});
最佳答案
这原来是 Nginx 服务器 block 配置问题。与 Express 路线无关。
这取决于服务器如何阻止以及您的应用程序需要设置。但就我而言:
删除了 try_files 的服务器指令。 (或者将其移到反向代理之后)根据您的需要。
关于node.js - 快速路由在本地计算机上按预期运行。但在 Nginx 上则不然,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48119503/