문제

I have recently started a new app with Express 4.0, and I really liked the new express.Router() thing.

Something that got me stuck for quite some time was the following behavior:

var app = require('express')(),
    router = express.Router();

router.get('/me', function(req, res, next) {
    if(someBoolean) {
        return next(); //here I expect to get a 404 error from express!
    }

    res.json({name: 'yourName'});
});

router.get('/:user_id', function() {
    //any code here!
});

app.use('/users', router);

I always used next() (in Express 3.x) to either call the next middleware or to force a 404 from the server.

Since /users/me and /users/45 are totally different routes and are not mounted in a way that one should come after another, I wonder why I get code in /users/:user_id evaluated after calling next() in /users/me.

Am I doing something wrong or things are supposed to work different in Express 4.0?

도움이 되었습니까?

해결책

This is working as expected. In Express 4 all middleware/routes are executed in the order that they are added to your app, so the path for your second router.get() is tested and matches because :user_id could be any kind of token, numeric or otherwise (basically any character that isn't /).

You can fix this at least in a couple of different ways:

  1. Don't call next() in your first router.get()
  2. Use a RegExp instead of a string to ensure that user_id only matches a numeric value. For example: router.get(/^\/(\d+)$/, function() {. However then you have to access the param via regexp group index instead of by a name: var user_id = req.params[0].
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top