redis.js
var ioRedis = require('ioredis');
var logger = require('./logger');
var redis = new ioRedis();
// 默许127.0.0.1:6379
// redis 链接毛病
redis.on("error", function (error) {
logger.error(error);
});
exports.redis = redis;
app.js
const index = require('./routes/index.js');
const app = express();
const cookieParser = require('cookie-parser')
const session = require('express-session');
const RedisStore = require('connect-redis')(session);
const http = require('http');
const httpServer = http.createServer(app);
var redis = require('./redis/redis.js').reids;
...其他中间件省略
app.use(cookieParser('sessiontest'));
app.use(session({
store: new RedisStore({
client: redis,
prefix: 'hgk'
}),
cookie: { maxAge: 1 * 60 * 60 * 1000 }, //默许1小时
secret: 'sessiontest',
resave: true,
saveUninitialized: true
}));
app.use('/', index)
//全局error中间件
app.use(function(err, req, res, next) {
console.log("Error happens", err.stack);
});
httpServer.listen(3000, function() {
console.log('HTTP Server is running on: http://localhost:%s', 3000);
});
第一次上岸
router.get('/login', function(req, res, next) {
// 从数据库中比对账号考证是不是胜利,如胜利保留用户信息
var user={
name:"Chen-xy",
age:"22",
address:"bj"
}
req.session.user=user;
res.json('上岸胜利')
});
须要上岸考证的路由
//猎取文章
router.get('/articals', function(req, res, next) {
if(req.session.user){
var user=req.session.user;
var name=user.name;
res.send('你好'+name+',迎接来到我的故里。');
}else{
res.send('你还没有登录,先登录下再尝尝!');
}
});
个人项目小博客链接https://github.com/hangaoke1/…
参考文章:
http://blog.csdn.net/u0126795…
http://wiki.jikexueyuan.com/p…
http://blog.csdn.net/yuanguoz…