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