mahdi pishguy mahdi pishguy - 3 months ago 6
Node.js Question

NodeJs what happen when Token is correct on next() method?

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()

Answer

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()

Comments