Home > Web Front-end > JS Tutorial > Implement login interception function under Express+Nodejs

Implement login interception function under Express+Nodejs

零下一度
Release: 2018-05-23 17:10:14
Original
1736 people have browsed it

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);//实际跳转
Copy after login

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");
  }
Copy after 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();
});
Copy after login

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();
});
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template