如何在Express.js的express-session中在1分钟的不活动后过期会话
在本文中,我们将看到如何在Express.js的express-session中在1分钟的不活动后过期会话。
先决条件
- 在Windows上安装Node.js
- 要设置编辑器中的Node项目,请参见此处。
需要的模块:
npm install express
npm install express-session
调用API:
var session = require('express-session')
在Express.js的express-session中,当用户无操作时,通过使用expires: 60000在中间件函数内设置1分钟后会话过期。
项目结构:
下面的示例说明了上述方法:
示例:
文件名:app.js
// Call Express Api.
const express = require('express'),
// Call express Session Api.
session = require('express-session'),
app = express();
// Session Setup
app.use(
session({
// It holds the secret key for session
secret: "I am girl",
// Forces the session to be saved
// back to the session store
resave: true,
// Forces a session that is "uninitialized"
// to be saved to the store
saveUninitialized: false,
cookie: {
// Session expires after 1 min of inactivity.
expires: 60000
}
})
);
// Get function in which send session as routes.
app.get('/session', function (req, res, next) {
if (req.session.views) {
// Increment the number of views.
req.session.views++
// Session will expires after 1 min
// of in activity
res.write(
'
<p> Session expires after 1 min of in activity: '
+ (req.session.cookie.expires) + '</p>
')
res.end()
} else {
req.session.views = 1
res.end(' New session is started')
}
})
// The server object listens on port 3000.
app.listen(3000, function () {
console.log("Express Started on Port 3000");
});
运行程序的步骤:
使用以下命令运行index.js文件:
node app.js
现在要设置您的会话,只需打开浏览器并键入此URL:
http://localhost:3000/session ****
输出: 1分钟不活动后,将开始新会话,旧会话将过期。