要实现超时用户被暂时注销,在首页登录自动跳转到之前页面功能。
基本实现思路是
1.用req.query.ReturnUrl获取此时页面的ReturnUrl
2.通过隐藏表格的形式将此参数传入到login.html页面中
3.在登录页面post请求中,用req.body.redirectUrl重新获取表格中url内容,并执行有无此redirectUrl判断,从而绘制不同页面。
判断是否登录代码
var isAuthenticated = function(req, res, next){
if(req.isAuthenticated()) return next();
res.redirect('/login?ReturnUrl=' + encodeURIComponent("/pages" + req.url));
};
在login.html中添加一个隐藏表格来获取参数
input type="hidden" name="redirectUrl" value="{{url}}"
在登录页面将参数传入
router.get('/login', function(req, res, next){
res.render('login', {url: req.query.ReturnUrl});
});
点击登录按钮时
在post请求中做一个判断,根据是否有req.body.redirectUrl跳转不同的页面
app.post('/login', function(req, res, next) {
var redirectUrl = req.body.redirectUrl;
passport.authenticate('local', function(err, user, info) {
if (err) { return next(err) }
if (!user) {
return res.render('login', { message: info.message })
}
req.login(user, function(err) {
if (err) { return next(err); }
return redirectUrl ? res.redirect(redirectUrl) : res.redirect('/');
});
})(req, res, next);
});
至此便完成了超时登录自动跳转到之前页面的功能。