在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。
- 如何将一个反应原生的js文件转换为纯javascript文件?
- EPERM:不允许操作,取消链接 – meteor错误
- 如何使用loopback和mongodb将嵌套对象中的属性转换为ObjectId?
- 使用webpack的require.ensure函数为javascript模块编写testing
- 计算JavaScript / NodeJS / Underscore中的散列值
- 将ES模块(.mjs)发布到NPMJS,并向后兼容节点<8.5.0
- 无法识别的input与webpack,less-loader和vuejs
- 是为每个需求创build一个node.js模块实例吗?
- Express – socket.io – 会话。 将用户标识作为套接字标识