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