How to count number of visits to a website using Express.js ?
Last Updated :
31 Mar, 2023
Session management can be done in node.js by using the express-session module. It helps in saving the data in the key-value form. In this article, we will see how to count the Number of views in Express Session in Express Js.
Prerequisites:
- Basic knowledge of Node.
- Node.js installed (version 12+).
- npm installed (version 6+).
To set up Node Project in Editor you can see here.
Installing requires modules:
npm install express
npm install express-session
Call API:
const session = require('express-session')
Example: This example illustrates the above approach.
Javascript
const express = require( 'express' ),
session = require( 'express-session' ),
app = express();
app.use(
session({
secret: "I am girl" ,
resave: true ,
saveUninitialized: false ,
cookie: {
})
);
app.get( '/session' , function (req, res, next) {
if (req.session.views) {
req.session.views++
res.write( '<p> No. of views: '
+ req.session.views + '</p>' )
res.end()
} else {
req.session.views = 1
res.end( ' New session is started' )
}
})
app.listen(3000, function () {
console.log( "Express Started on Port 3000" );
});
|
Run the index.js file using the below command.
node app.js
Now to set your session, just open the browser and type this URL.
http://localhost:3000/session
Output:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...