nodejs+express+express-session+redis 实现登陆验证

in 编程
关注公众号【好便宜】( ID:haopianyi222 ),领红包啦~
阿里云,国内最大的云服务商,注册就送数千元优惠券:https://t.cn/AiQe5A0g
腾讯云,良心云,价格优惠: https://t.cn/AieHwwKl
搬瓦工,CN2 GIA 优质线路,搭梯子、海外建站推荐: https://t.cn/AieHwfX9

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

关注公众号【好便宜】( ID:haopianyi222 ),领红包啦~
阿里云,国内最大的云服务商,注册就送数千元优惠券:https://t.cn/AiQe5A0g
腾讯云,良心云,价格优惠: https://t.cn/AieHwwKl
搬瓦工,CN2 GIA 优质线路,搭梯子、海外建站推荐: https://t.cn/AieHwfX9
扫一扫关注公众号添加购物返利助手,领红包
Comments are closed.

推荐使用阿里云服务器

超多优惠券

服务器最低一折,一年不到100!

朕已阅去看看