Express 4中间件未在DigitalOcean服务器上调用路由 [英] Express 4 middleware not calling routes on DigitalOcean server
问题描述
我正在用io.js和Express 4创建一个API,我不知道为什么这不起作用.我目前正在DigitalOcean Droplet(Ubuntu 14.04)上运行该程序,它没有调用next()方法,因此永远不会被调用/执行.该程序由具有https://<redacted>/asdf
的nginx的反向代理路由.
I'm messing around with creating an API with io.js and Express 4, and I have no idea why this isn't working. I am currently running the program on a DigitalOcean droplet (Ubuntu 14.04) and it is not calling the next() method never gets called/executed. The program is being routed to by a reverse proxy with nginx at https://<redacted>/asdf
.
var express = require('express');
var app = express();
var port = process.env.PORT || 3000;
var router = express.Router();
router.use(function(req, res, next) {
console.log("Request received.");
next();
});
router.post('/login', function(req, res) {
console.log('Route /login accessed');
});
app.use('/', router);
app.listen(port);
console.log("Server started on port " + port + ".");
当我在我的Droplet上运行程序并将POST请求发送到https://<redacted>/asdf/login
时,控制台将打印出已接收到请求",但不会打印出已访问路由/登录".奇怪的是,当将发布请求发送到http://localhost:3000/login
时,这在我的本地计算机上运行良好.是我做错了什么,还是我不知道的已知事情?
When I run the program on my droplet and send a POST request to https://<redacted>/asdf/login
, the console prints out "Request received" but does not print out "Route /login accessed". The odd thing is that this works perfectly fine on my local machine when a post request is sent to http://localhost:3000/login
. Is there something I am doing wrong or is this a known thing that I am not aware of?
推荐答案
Express在映射路由时使用请求的url
属性,我怀疑您的nginx反向代理没有从中删除/asdf
根.如果是这样,您的url路径将是/asdf/login
,这将解释为什么未调用/login
后处理程序的原因.要测试此假设,您可以尝试将反向代理根目录添加到您的use
中,如下所示:
Express uses the request's url
property when mapping routes, and I suspect that your nginx reverse proxy isn't removing the /asdf
root from it. If so, your url's path would be /asdf/login
which would explain why your /login
post handler isn't being invoked. To test this hypothesis you could try adding the reverse proxy root to your use
like this:
app.use('/asdf', router);
在这种情况下,要解决此问题,您可以配置nginx像这样为您重写网址
If this is the case, to fix this problem, you can configure nginx to rewrite the url for you like this
location /asdf {
rewrite /asdf(.*) $1 break;
proxy_pass http://localhost:3200;
proxy_redirect off;
proxy_set_header Host $host;
}
更多详细信息: https://serverfault.com/questions/379675/nginx-reverse-proxy-url-rewrite http://wiki.nginx.org/HttpRewriteModule#rewrite
这篇关于Express 4中间件未在DigitalOcean服务器上调用路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!