1

i'm newbie in using Authenticate a Node.js API with JSON Web Tokens, i read this document on scotch.io but i cant understand when Token is correct what happen after next() method

apiRoutes.use(function(req, res, next) {

    // check header or url parameters or post parameters for token
    var token = req.body.token || req.param('token') || req.headers['x-access-token'];

    // decode token
    if (token) {
        // verifies secret and checks exp
        jwt.verify(token, app.get('superSecret'), function(err, decoded) {          
            if (err) {
                return res.json({ success: false, message: 'Failed to authenticate token.' });      
            } else {
                // if everything is good, save to request for use in other routes
                req.decoded = decoded;  
                next();
            }
        });

    } else {
        ...
    }

});

apiRoutes.get('/', function(req, res) {
    ...
});

apiRoutes.get('/users', function(req, res) {
    ...
});

apiRoutes.get('/check', function(req, res) {
    ...
});

app.use('/api', apiRoutes);

app.listen(port);

User must be pass other request after that (my mean is after token is correct)?

i think in this sample code / route will be call after check token and it was correct,ok? how can i choose other method to call, because / is calling after next()

mahdi pishguy
  • 994
  • 1
  • 14
  • 43

1 Answers1

1

actually next() asking for nodejs to go on for next step it's whatever in node.js async loop. Javascript actually single threaded so next will call whatever method placed at stack. if you will not call next() your program will stuck. and will not call any other method after this token middleware which you have passed to .use

In this particular scenario it will call the next route after verified by this token middleware, which you are passing as a anonymous function.

also have a look at this method javascript node.js next()

Community
  • 1
  • 1
owais
  • 4,752
  • 5
  • 31
  • 41
  • i think in this sample code `/` route will be call after check token and it was correct,ok? how can i choose other method to call, because `/` is calling after `next()` – mahdi pishguy Aug 05 '16 at 08:41
  • It's not necessary that it will call / route. Every method executed by user and is using apiRouter will go through this middleware. it can be / /users /whatever and so on. – owais Aug 05 '16 at 08:55
  • then this is only middleware and for each request called automatically is it right? passed method after that may be were something – mahdi pishguy Aug 05 '16 at 09:07
  • off-course. also you can pass any number of middlewares. – owais Aug 05 '16 at 09:12