session in node.js

Session Management in Node.js using ExpressJS and Express Session | Engineering Education (EngEd) Program | SectionThis tutorial will help the reader develop a session based authentication system and go over how to manage sessions using Express.js and Express Session in Node.js.https://www.section.io/engineering-education/session-management-in-nodejs-using-expressjs-and-express-session/Pre-reading: a really good and clear article about the differences between session and cookie. 

注意: 现在的express-session module do not need cookie-parser anymore. 在这个文章中的cookie-parser可省略

Setting up the required environments and libraries

npm init –y

This will generate a package.json file that will manage the dependencies for this project’s tutorial.

npm install express express-session

Express-session options and how to use them 

配置session的中间件

app.use(session({
    secret: 'thisisasecret!',
    resave: false,
    saveUninitialized: true,
    cookie:{
        httpOnly: true,
        expires: Date.now() + 1000*60*60*24*7,
        maxAge: 1000*60*60*24*7
    }
}))
  • secret - a random unique string key used to authenticate a session. It is stored in an environment variable and can’t be exposed to the public. The key is usually long and randomly generated in a production environment. 现在就随便自己编个就行。激活session的力量!

  • resave - 强制保存session,即使它没有变化

  • saveUninitialized - 强制将未初始化的session储存

  • 以上cookie设置expires date是一天。The browser will delete the cookie after the set duration elapses. The cookie will not be attached to any of the requests in the future. In this case, we’ve set the maxAge to a single day as computed by the following arithmetic. 

    // creating 24 hours from milliseconds
    const oneDay = 1000 * 60 * 60 * 24;

现在暂时没有储存在database里,现在是非生产环境,所以直接存电脑memory了。production environment另说

同时注意一下代码: useFindAndModify 需要加上并改为 false

mongoose.connect('mongodb://127.0.0.1:27017/yelp-camp', {
    useNewUrlParser: true,
    useUnifiedTopology: true,
    useFindAndModify:false 
});

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值