【发布时间】:2015-11-10 20:44:46
【问题描述】:
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呢?
【问题讨论】:
-
所以
isAuthenticated返回next()返回的任何内容。请注意,这可能不是一个有用的值。 -
stackoverflow.com/questions/16810449/… 的可能重复项,但这是一个有效的好问题
-
在 express 中间件的上下文中,如果该特定的中间件落入其中任何一个 if 语句,它就会停止执行。调用
next告诉 express '我在这里完成移动' 但是没有return它可以调用next但也尝试执行重定向。
标签: javascript node.js