The session variable fails to update across several requests

I am looking to track the number of requests sent by a browser and store it in the session. Below is the code snippet I have written:

import express from 'express';
import expressSession from 'express-session';
import path from "path";

const app = express();

app.use(expressSession({
    secret:"cat keyboard",
    resave:true,
    saveUninitialized:true
}));


app.use((req,res,next)=>{
    console.log(req.path)
    console.log("before", req.session?.count)
    if (req.session) {
        if (req.session.count) {
          req.session.count += 1;
        } else {
          // vistCounter += 1
          req.session.count = 1;
        }
      } else {
        console.log("no session",req.session)
      }
      console.log("after", req.session?.count)
      next();
})

app.use(express.static('public'));

app.use((req,res,next)=>{
    res.sendFile(path.join(__dirname + "/public","404.html"));
})

app.listen(1234,()=>{
    console.log("server run");
});

When accessing localhost:1234, the following output is displayed:

/
before undefined
after 1

/index.css
before 1
after 2

/index.js
before 1 (it should be 2)
after 2

/favicon.ico
before 2
after 3

It appears that the browser made requests for "/", "index.css", "index.js", and "favicon.ico". However, the counter does not update between the index.css and index.js requests. The counter should increment to 2 after the index.css request, leading to a value of 2 before the index.js request adds 1 more. Instead, the counter remains at 1 during the "index.js" request. Can someone clarify why the counter is not updating after the index.css request but before the index.js request?

Answer №1

In my opinion, the issue lies in the speed at which the requests are being made. The third request is occurring before the second one has a chance to increment your variable. It would be wise to introduce a delay between each request to ensure that each execution is fully completed before moving on to the next request.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Obtaining JSON Data Using WinJS.xhr():

I'm encountering difficulties with retrieving chat messages using winjs.xhr: function getMessage() { var time = MESSAGE_RETURNED.unixtime; if (time == 0) { time= window.parent.SESSION.unixtime; } WinJS.x ...

Update the icon with the adjusted API information

I am currently working on a website that revolves around the theme of weather. I have reached a point in the development process where I need the icon to change according to the current weather conditions. let updateIcon = () => { let ic ...

Implementing event dispatch on Push notifications received with Workbox

In my VueJS component, I have set up a listener for the pushMessageEvent event: <template> <div> <VueBotUI :options="options" :is-open="isOpen" :bot-typing="botTyping" :inpu ...

Accessing the public API for Anchor podcasts

Is there a way to retrieve the list of episodes from my anchor account using JavaScript? Anchor provides an embed code in the form of an iframe. Would it be possible to obtain the episode names through a public API? I need to display the full list of epi ...

Guide to setting up Gatsby CLI and Gatsby version 2

Currently, I am working on a project that utilizes Gatsby v2 in its package.json file. However, to run the project, I need to globally install Gatsby-cli as per the documentation. Strangely, the global installation of Gatsby-cli also installs Gatsby v4, ca ...

Decipher complex JSON structures

I am working with a multi-level JSON structure: { "1":{ "name":"PHP", "slug":"/tag/php", "type":"Tag" }, "2":{ "name":"JavaScript", "slug":"/tag/javascript", "type":"Tag" }, "3":{ ...

Encountered an error: ReferenceError - 'global' is not defined while configuring a node/express server and webpack

I am in the process of creating a simple script to fetch data from an API and process it. To enable CORS, I have set up a node/express server and linked it to my Webpack bundle. However, I encountered an error stating global is not defined. Through some re ...

Obtain information stored locally when an internet connection is established

I'm currently facing an issue with my Local Storage data retrieval process in Vuejs while being online. My ToDo app setup consists of Vuejs, Laravel, and MySQL. When the internet connection is available, I store data in localStorage. The ToDo app has ...

Is there a way to determine if a Dojo dialog has been successfully loaded on the page?

I have a function that needs to close a Dojo dialog if it is currently open. How can I determine if a dojo dialog is active? Should I rely on pure JavaScript and check for its existence by ID? if (dijit.byId("blah") !== undefined) { destroyRecursive ...

JavaScript incorporates input range sliding, causing a freeze when the mouse slides rapidly

Currently working on a custom slider and encountering an issue. When quickly moving the mouse outside the slider's range horizontally, exceeding its width, the slider doesn't smoothly transition to minimum or maximum values. Instead, there seems ...

Error Alert: The index "dateform" is not defined

I have set up two calendar date pickers and am trying to obtain the input data or retrieve the "post" date. However, upon running my code, I am encountering the following error message: Notice: Undefined index: dateform I am puzzled by this error because ...

Setting up models routes in Node and Express: A comprehensive guide

In my model file, I have a set of routes exported like this: const newsRoutes = (app: express.Application): void => { app.get('/news', readAll); app.get('/news/:id', readOne); }; To use these routes, I import the function and pa ...

What is the best way to activate an event listener only after a button has been clicked?

Currently, I am developing a game that includes a timer and an event listener that notifies the user not to switch tabs. However, I am facing an issue where the event listener triggers before the game's start button is clicked. Is there a way in JavaS ...

Here is a list of selections that can be easily removed and have a child selection added

While this question may be a bit ambiguous, please bear with me as I explain my dilemma. I am utilizing React to develop a component that accepts an object with keys and values as a prop. Each value within the object is a list of values. This component ne ...

Looking to test form submissions in React using Jest and Enzyme? Keep running into the error "Cannot read property 'preventDefault' of undefined"?

Currently, I am developing a test to validate whether the error Notification component is displayed when the login form is submitted without any data. describe('User signin', () => { it('should fail if no credentials are provided&apos ...

Steps for creating a link click animation with code are as follows:

How can I create a link click animation that triggers when the page is loaded? (function () { var index = 0; var boxes = $('.box1, .box2, .box3, .box4, .box5, .box6'); function start() { boxes.eq(index).addClass('animat ...

Encountered a 404 error (not found) while making a GET request with axios

I encountered an issue with my pizza shop application built with Next.js. Whenever I run the app on my computer, I come across this error: https://i.sstatic.net/tsQzZ.png The error disappears after refreshing the page. Here is my index.js file: import ax ...

Ajax request terminates once PHP has looped for a specific duration of time (2 minutes)

My challenge involves a button that is responsible for checking over 300 posts for a specific value and other conditions using about 20 if-else statements. Strangely, the ajax call initiated by this button halts after completing around 73 loops within a sp ...

Creating React components through the use of the map function

Utilizing the hackernews api, I am attempting to extract the "data" property from my response object in order to display each story title individually on the browser. Initially, the data is structured as an array of id's representing individual storie ...

Retrieving the value of a checkbox in a React custom checkbox component

I am facing an issue with my dynamic checkbox functionality. I need to update the state based on the selected options only, but my attempt to filter the state on change is not working as expected. Can someone help me identify what went wrong? const check ...