如何使用Express.js计算网站访问次数
可以使用express-session模块在node.js中进行会话管理。它可以以键值形式保存数据。在本文中,我们将看到如何在Express Session中计算访问次数。
先决条件:
- 对Node的基本了解。
- 已安装Node.js(版本12+)。
- 已安装npm(版本6+)。
安装所需模块:
npm install express
npm install express-session
调用API:
const session = require('express-session')
示例: 此示例说明以上方法。
// 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: {
})
);
// 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++
// Print the views.
res.write('<p> No. of views: '
+ req.session.views + '</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
输出: