Express 4 middleware not calling routes on Digital

2019-08-01 07:19发布

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条回答
狗以群分
2楼-- · 2019-08-01 07:40

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

查看更多
登录 后发表回答