var express = require('express'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); var session = require('express-session'); var swig = require('swig'); var user = require('./modules/user'); var app = express(); //设置swig模板方法; app.engine('html', swig.renderFile); app.set('view engine', 'html'); app.set('views', __dirname + '/views'); //console.log(user) app.use(session({ secret: 'hubwiz app', //secret的值建议使用随机字符串 saveUninitialized: true, cookie: { secure: false } // 过期时间(毫秒) })); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.use(cookieParser()); app.get('/', function (req, res) { if (req.session.sign) {//检查用户是否已经登录,如果已登录展现的页面 console.log(req.session);//打印session的值 res.send("已登录"); } else {//否则展示index页面 res.render('index', {title: 'index'}); } }); app.get('/out',function(req,res){ req.session.destroy(); res.send("out"); }); app.post('/login', function (req, res) { //登录的数据和user.json中的数据进行对比 if (req.body.password != user.hubwiz.password || req.body.user != user.hubwiz.name ) { res.end('sign failure'); } else { req.session.sign = true; req.session.name = user.hubwiz.name; res.send('welecome <strong>' + req.session.name + '</strong>,<a href="/out">登出</a>'); console.log('成功登录'); } }); app.get("/app",log,function(req,res){ res.send("登录app"); }); //登录验证函数; function log(req,res,next){ console.log('通过log验证'); if(req.session.sign){ return next(); }else{ res.redirect('/'); return null; } } app.listen(8080);