node.js - node express order routes -


i have routes setup that:

app.use('/', index); app.use('/auth', auth); app.use(requesthandlers.authorize);     app.post('/users', users);     // catch 404 , forward error handler app.use(requesthandlers.notfound); 

my handlers:

export function authorize(req: request, res: response, next: function) {      // check header or url parameters or post parameters token     var token = req.body.token || req.query.token || req.headers['x-access-token'];     //token logic   };  export function notfound(req: request, res: response, next: function) {     var err: = new error('not found');     err.status = 404;     next(err);   } 

so have no problems handle defined routes when accessing not existed routes requesthandlers.authorize getting executed first. if route not existed want fire app.use(requesthandlers.notfound);

how can that? best approach without putting custom logic on routes? may there way check if route defined?

when app.use(fn) you're saying "use middleware function every request".

seeing want authorize function run on specific routes, should add routes, using following method:

app.get('/', middleware, fn) 

…so specific example:

app.get('/', requesthandlers.authorize, index) app.get('/users', requesthandlers.authorize, users) 

the middleware argument when creating route can function (req, res, next) or can array of functions.

more info here: http://expressjs.com/en/guide/routing.html#route-handlers


Comments

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -