在nodejs混乱中返回next()

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()是让stream程跳转到下一个中​​间件或函数,但为什么它需要return next()以上?

这是一个约定退出函数退出。 另一种方法是使用if-else if-else而不是if 。 在这种情况下,您只需要退出该function,并在您的中间件链上继续前进。

你会经常看到这种模式。 例如,这是很常见的:

 someFunction(function(err, result) { if (err) { return console.error(err); } console.log(result); }); 

与此相比,它嵌套更less,对大多数人来说更容易:

 someFunction(function(err, result) { if (err) { console.error(err); } else { console.log(result); } }); 

第一种模式还可以防止在if-else -logic中出现错误时,无意中调用next()两次甚至更多次。 这就是你发布的next()应该不会发生的事情。 它可以调用next()并在任何情况下仍然会导致redirect。