Nodejs middleware Intercept, Express does not login can not enter the background page

Source: Internet
Author: User

22. Setting up interception

Only login to enter the background page, not login can not enter

如果登陆成功, 写入session, 参数 uid    uid=123dsfjksldfjsl
检测登陆, 请求中 session 是否包含 uid 参数.

1.app.js Portal Page

设置session 的uidapp.use(session({  secret: ‘bitiancanshu‘,  // 以下是选填参数,但是不填会提示警告 start  resave: false,  saveUninitialized: false,    //  设置connect.sid    name: ‘luyao‘,  // 设置生命周期  cookie: { maxAge: 60000000 },}))

2.index.js front Page

        当登录成功时     if(user.password == md5(fields.password)){          // 登录成功,写入session;          req.session.uid = ‘adminuid‘;          res.render(‘commen/success‘,{msg:‘恭喜您,登录成功‘,time:3000,url:‘/admin‘});        } else {          res.render(‘commen/error‘, { msg: ‘对不起,密码错误,请核对后重新输入‘, time: 3000, url: ‘/login‘ });        }

3.app.js

//  拦截app.use(function(req, res, next) {  var url = req.url;  // 判断不拦截的路由 出/login和/之外的都拦截  if (url != ‘/login‘ && !req.session.uid && url != ‘/‘) {    console.log(‘跳转到登录页‘);    res.render(‘commen/error‘, { msg: ‘对不起,请登录个人信息,否则无法进入后台管理页面‘, time: 3000, url: ‘/login‘ });    return;  }  next();});*****************************注意*****************************引入路由规则,一定要在中间件和设置session的后面,否则无效,切记app.use(‘/‘, indexRouter);app.use(‘/‘, adminRouter);

Nodejs middleware Intercept, Express does not login can not enter the background page

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.