nodejs+express+express-session+redis 實現登錄驗證

redis.jshtml

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.jsnode

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);
});

第一次登錄git

router.get('/login', function(req, res, next) {
    // 從數據庫中比對帳號驗證是否成功,如成功保存用戶信息
    var user={
        name:"Chen-xy",
        age:"22",
        address:"bj"
    }
  req.session.user=user;
  res.json('登錄成功')
});

須要登錄驗證的路由github

//獲取文章
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/...redis

參考文章:
http://blog.csdn.net/u0126795...
http://wiki.jikexueyuan.com/p...
http://blog.csdn.net/yuanguoz...數據庫

相關文章
相關標籤/搜索