https://github.com/hwz/chirp/blob/master/module-5/completed/routes/api.js
function isAuthenticated (req, res, next) {
// if user is authenticated in the session, call the next() to call the next request handler
// Passport adds this method to request object. A middleware is allowed to add properties to
// request and response objects
//allow all get request methods
if(req.method === "GET"){
return next();
}
if (req.isAuthenticated()){
return next();
}
// if the user is not authenticated then redirect him to the login page
return res.redirect('/#login');
};
为什么作者做return next()
而不是next()
?我知道next()
是为了让流程跳转到下一个中间件或函数,但是为什么上面的next()
需要一个return
呢?
最佳答案
在函数前面加上return
是一种惯例。另一种方法是使用 if-else if-else
而不仅仅是 if
。在这种情况下,您只想退出该函数并在您的中间件链上更进一步。
您会经常看到这种模式。例如,这是很常见的:
someFunction(function(err, result) {
if (err) {
return console.error(err);
}
console.log(result);
});
与此相比,它更少嵌套并且对大多数人来说更容易阅读:
someFunction(function(err, result) {
if (err) {
console.error(err);
} else {
console.log(result);
}
});
第一个模式还可以防止您意外调用 next()
两次或更多次,以防您的 if-else
逻辑出现错误。 在您发布的那种情况下,这正是 next()
不应该发生的事情。它可以调用 next()
并且仍然会导致重定向无论如何。
关于javascript - 在 nodejs 困惑中返回 next(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33629897/