1
const express = require("express");
const app = express();
var i = new Number;
i=0;
app.get("/", function(req, res){
    i++
    console.log(i);
});
app.listen(8080);

I created a very small node js project. I have a problem. when I create a variable like above, it doesn't evaluate for each user separately. that is, when a user requests a get, I want it to be 1 each time. Sample my problem is that when a jack user enters a site, if he doesn't log out, someone who enters the site's home page from another device enters his account with jack. how can I do that?

1 Answers1

0

The simplest answer for your question is to simply declare and increment the variable inside the function passed to app.get, but I'm going to assume that you would like a situation where, for a given user's series of requests, the number will increment.

The simplest way to do this is using a server side session, which is provided by the express-session library. Additionally, in order for this to work, you need to call res.end() in order to send the cookie associated with the server session back to the user's browser. More information on sessions generally can be found here.

Below is code to replicate the intent of what you have there, but incrementing for each request from a unique browser instance (identified by the same cookie value associated with the server session):

const express = require('express');
const session = require('express-session');

const app = express();

app.use(session({
  resave: false,
  saveUninitialized: true,
  secret: 'secret',
  cookie: {
    maxAge: 60000
  }
}));

app.get('/', function(req, res){
  if (!req.session.value) {
    req.session.value = 0;
  }

  req.session.value++;
  console.log(req.session.value);
  res.end();
});

app.listen(8080);
msbit
  • 4,152
  • 2
  • 9
  • 22
  • my problem is that when a jack user enters a site, if he doesn't log out, someone who enters the site's home page from another device enters his account with jack. – Yusuf Cıbıl Nov 04 '19 at 14:55
  • @YusufCıbıl in general, it sounds like you are leaking the state outside of the request (eg, having the `i` variable outside of the request handlers). Using the session as I've shown covers this a bit, as it fetches the session associated with the browser and pulls the value from there, instead of manipulating the global variable. – msbit Nov 06 '19 at 00:18