How to count number of visits to a website using Express.js ?
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
// 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" ); }); |
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:
Please Login to comment...