路由在我的本地机器上按预期提供服务。但不提供/public 或/api 路由。
我已经为 node.mydomain.com 设置了一个服务器块,安装了一个节点应用程序,并且对于 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服务器块
#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 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服务器块配置问题。与快速路线无关。
这取决于服务器块和应用程序需要设置的方式。但就我而言:
删除了try_files的服务器指令。(或在反向代理后将其向下移动(根据您的需要。