Express 4 middleware not calling routes on DigitalOcean server

穿精又带淫゛_ 提交于 2019-12-13 18:16:05

问题


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 + ".");

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?


回答1:


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);

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;
}

More details: https://serverfault.com/questions/379675/nginx-reverse-proxy-url-rewrite http://wiki.nginx.org/HttpRewriteModule#rewrite



来源:https://stackoverflow.com/questions/30194048/express-4-middleware-not-calling-routes-on-digitalocean-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!