首先定义了一个函数
function checkLogin(req, res, next) {
if (!req.session.user) {
req.flash('error', '未登录!');
res.redirect('/login');
}
next();
}
然后下面这样的用法每太看明白啊,请问这样的写法是javascript的语法糖还是node的语法糖
app.get('/reg', checkNotLogin);
app.get('/reg', function (req, res) {
res.render('reg', {
title: '注册',
user: req.session.user,
success: req.flash('success').toString(),
error: req.flash('error').toString()
});
});
求各位大大解释一下或者给个相关链接参考一下
巴扎黑2017-04-10 12:51:12
先给纠正一下,你示例中的这个这个代码是不对的:
function checkLogin(req, res, next) {
if (!req.session.user) {
req.flash('error', '未登录!');
res.redirect('/login');
// 这里应该加个 return ,否则会出错(即 res.redirect() 和 next()不能同时执行)
}
next();
}
或者写成:
function checkLogin(req, res, next) {
if (!req.session.user) {
req.flash('error', '未登录!');
res.redirect('/login');
} else {
next();
}
}
以下代码的用法不是JavaScript或者Node.js的语法糖,仅仅是Express.js的一个特性而已,与语法什么的没有任何关系:
app.get('/reg', checkNotLogin);
app.get('/reg', function (req, res) {
res.render('reg', {
title: '注册',
user: req.session.user,
success: req.flash('success').toString(),
error: req.flash('error').toString()
});
});
与下面这样的写法作用是一样的:
app.get('/reg', checkLogin, function (req, res) {
res.render('reg', {
title: '注册',
user: req.session.user,
success: req.flash('success').toString(),
error: req.flash('error').toString()
});
});
另外提醒一下, 贴代码时要注意一下格式,缩进神马的不要搞错
伊谢尔伦2017-04-10 12:51:12
Express 框架的 API,说白了就是钩子链。
app.use([path, ]hook)
app.get(path[, hook1, hook2, hook3, ...], handler)
任何一个钩子,只要调用了 res.end()
(或者 res.send()
、res.render()
之类最终会调用 res.end()
的方法)后,就将内容返回给用户,中断后续的钩子;如果调用 next()
则把请求传递给下一个钩子,一直传递到最后的 handler
。
app.use(function (req, res, next) {
// I'm hook 1, I won't do anything.
next()
})
app.use(function (req, res, next) {
// I'm hook 2, I'll break the chain
res.send('Oops! Broke at hook 2')
})
app.get('/', function (req, res) {
// Handler for path /
// We responsed the user at hook 2,
// so requests would never reach this handler
res.send('You\'ll never see this')
})
PS:十分喜欢 SegmentFault 的文字样式和 GFM,顿时充满了编写回答的欲望啊~
迷茫2017-04-10 12:51:12
你定义的是checkLogin
还是checkNotLogin
额..
还有你到底哪里没明白了?
如果你是说/reg
匹配了多个函数的话请自觉看checkLogin
的倒数第二行next();
,这个的作用就是当有多个匹配的时候再执行完一个的时候不做跳转继续进行下一个匹配的操作。
链接的话你可以谷歌一下,郭家宝的Node.js入门那本书上也有写这个(《Node.js开发指南》95页-96页:控制权转移)。
如果不是的话就请忽略我的答案吧╮(╯▽╰)╭