Home Ask Login Register

Developers Planet

Your answer is one click away!

sreginogemoh February 2016

node express order routes

I have my routes setup like that:

app.use('/', index);
app.use('/auth', auth);
app.post('/users', users);    
// catch 404 and forward to error handler

My handlers:

export function Authorize(req: Request, res: Response, next: Function) {

    // check header or url parameters or post parameters for 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: any = new Error('Not Found');
    err.status = 404;

So I have no problems to handle any defined routes but when I am accessing any not existed routes the RequestHandlers.Authorize always getting executed first. But if the route is not existed I want to fire app.use(RequestHandlers.NotFound);

How can I do that? What is the best approach without putting much custom logic on the routes? May be there is the way to check if route is defined?


Ben Gourley February 2016

When you do app.use(fn) you're saying "use this middleware function for every request".

Seeing as you only want the authorize function to run on specific routes, you should add it to only those routes, using the following method:

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

…so for your specific example:

app.get('/', RequestHandlers.Authorize, index)
app.get('/users', RequestHandlers.Authorize, users)

The middleware argument when creating a route can be a function (req, res, next) or it can be an array of functions.

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

Post Status

Asked in February 2016
Viewed 1,760 times
Voted 10
Answered 1 times


Leave an answer

Quote of the day: live life