express 4 中 session的处理(仅为博主笔记)

1、app.js

var express = require('express')
var app = express();
var routers = require('./router/index')
var express_session = require('express-session'); app.use(express_session({
secret:'keyboard cat',
resave:false,
saveUninitialized:true
})); app.use('/', routers);

2、auth.js(前端post数据,调用这个方法)

var userAuth = funtion (req, res, next) {
if(req.body.username == 'admin' && req.body.password == 12345) {
//这里是重点:::::测试时,接收到前端页面post来的数据后,随便赋个值给req.session.user.
          req.session.user = {test:1}
res.sendStatus(200);
}
}

3、index.js(app.js的routers)

var express = require('express');
var router = express.Router();
//use/get/post/all,都可以直接放两个函数,要记得用next();才会在第一个函数结束后继续进入下一个函数
router.use('/pageIndex', anthentication, router);
function authentication(req, res, next) {
if(req.session.user){
next();
} else {
res.redirect('/login');//redirect要加'/',render渲染时不用
}
} module.export = router;

  

上一篇:2018 German Collegiate Programming Contest (GCPC 18)


下一篇:知乎:在卡内基梅隆大学 (Carnegie Mellon University) 就读是怎样一番体验?