The website is being implemented.
You are about to display [Number of Visitors] on the main screen of the website.
By what standard do you usually count the number of visitors? ex) Daily count based on visitor IP, daily count based on visitor ID, etc.
I want to know how to implement it according to 1. I don't know if I have to go to DB, or cookies, or sessions.
I found an example like this, is the method below a good one?
var count = 0;
app.get('/', function(req, res, next) {
count++;
res.send();
next();
});
app.get('/count', function(req, res) {
res.send("" + count + " visitors.");
});
I'm sorry that the question may be ambiguous because I don't know anything yet.
Thank you.
node.js web server
If you do it according to the method you posted, the number will keep going up if you reload the page.
You can also count the dates you visited most recently in a cookie only when the dates change. Please refer to the following code. I used cookie-session.
var cookieSession = require('cookie-session')
var express = require('express')
var app = express()
var count =0;
app.set('trust proxy', 1) // trust first proxy
app.use(cookieSession({
name: 'session',
keys: ['key1', 'key2']
}))
app.use(function (req, res, next) {
var date = new Date();
var today=date.getYear()+" "+date.getMonth()+" "+date.getDate();
// // Update views
console.log(req.session.lastVisit);
if(req.session.lastVisit != today){
req.session.lastVisit = today;
count++;
}
// // Write response
res.end(count + 'visit')
})
app.listen(3000)
For your information, you have to reset the count to 0 every day.
© 2024 OneMinuteCode. All rights reserved.