Express / Connect Middleware Management Procedure

I am trying to add middleware for authentication that should prevent access to part of the site:

app = express() .get('/api/test', function (req, res) { ... }) .use('/api', function (req, res, next) { if (req.param('key')) { next(); } else { res.json(401, { message : 'Authentication failed' }); res.end(); } }) .get('/api/data', function (req, res) { ... }); 

And my expectation is that calls to / api / data will be processed first by the verification key, and then (if it succeeds) by the / api / data handler. But instead, the request is first processed by "/ api / data".

Checker seems to work for / api / something _that_does_not_exist, but not for / api / something _that_exist.

Perhaps I missed something in the Express / Connect documentation?

Update . I tracked this to the point that the first get / post call initializes the middleware of the router so that it runs first.

+4
source share
1 answer

Once you declare a route, Express inserts the router middleware router middleware stack at this point when you configure the application.

In your case, since you insert .get('/api/test', ...) before inserting the key verification middleware, the middleware of the router gets up and will take precedence (also for the /api/data route, which you declare later) and your key check is never called.

Here are two solutions:

 // separate middleware, used for all routes that need checking var keyChecker = function(req, res, next) { ... }; app.get('/api/test', function(req, res) { ... }); app.get('/api/data', keyChecker, function(req, res) { ... }); // or, as an alternative, create a 'catch-all' route between the routes that don't // need to be checked, and the ones that should; this will also match non-existing // routes (like '/api/foobar'), which might or might not be an issue; app.get('/api/test', function(req, res) { ... }); app.all('/api/*', function(req, res, next) { // 'all' means 'all methods' // keychecker code }); app.get('/api/data', function(req, res) { ... }); 

A third solution would be to explicitly check for /api/test in the key verification tool itself ( req.path === '/api/test' ) and simply call next() if it matches.

+5
source

All Articles