Home > Article > Web Front-end > Implement login interception function under Express+Nodejs
This article mainly introduces the login interception implementation code under Express+Nodejs. The editor thinks it is quite good, so I will share it with you now and give it as a reference. Let’s follow the editor and take a look.
It turned out that I never knew how to add an interceptor similar to Struts2 in Express+Nodejs (because the login interception function is required).
I used to think that adding a similar transfer to the routerroutingcontrol code (each one is very troublesome)
app.get('/show', controllers.checkLogin);//登录验证 app.get('/show', controllers.showList);//实际跳转
Or maybe For example, in some projects, the following verification is added to each controller method (too cumbersome)
if (!req.session.user) { return res.redirect("/login"); }
I recently found a code snippet that used session before, and suddenly I had an enlightenment! !
//session app.use(function (req, res, next) { var err = req.flash('error'); var success = req.flash('success'); res.locals({ user:req.session.user, navSide:req.session.navSide, error:err.length ? err : null, success:success.length ? success : null }); next(); });
Isn’t this just an interceptor~囧~
Slightly modified
//登录拦截器 app.use(function (req, res, next) { var url = req.originalUrl; if (url != "/login" && !req.session.user) { return res.redirect("/login"); } next(); });
After testing, it was successful
The above is the detailed content of Implement login interception function under Express+Nodejs. For more information, please follow other related articles on the PHP Chinese website!