Establishing the Session Once Headers are Established

Currently, I am working on implementing an asynchronous method that involves making a POST call to a specific API to fetch data and then storing the result in the user's session. Although the task itself seems straightforward, it becomes challenging when approached in a 'fire-and-forget' style.

Instead of waiting for the response from the external API, I prefer to allow the user to continue navigating to their requested page without any delays. Once the data is retrieved, I want it to be saved in the session.

While everything appears to be functioning correctly, the issue arises when I set the session and move on to the next route, where everything seems to disappear as if it was never stored in the first place. Even after debugging the code that shows no errors, I suspect there might be an issue with setting the session after the response headers have been already set. However, it's puzzling why this would cause a problem.

My current setup involves using nodejs with express for server-side programming and mongodb for handling sessions and databases.

router.get('/myroute', function(req, res, next) { 
  request({
        url: endpoint,
        method: "POST",
        json: true,
        body: jsonData
    }, function(error, response, body) {
    req.session.mykey = 'some response';
  });
  res.redirect('/otherroute');
});

router.get('/checkresult', function(req, res, next) { 
  res.json(req.session.mykey);
});

Answer №1

You may need to explicitly invoke the save function.

function(error, response, body) {
    req.session.mykey = 'some response';
    req.session.save();
}

Find more information about saving sessions on this link

The session data save method is automatically triggered at the end of the HTTP response if any changes have been made

In your particular case, the automatic save operation might be happening too early.

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

Having trouble with Chai-http functionality

Encountering an error message stating Uncaught TypeError: Cannot read property 'apply' of undefined at Immediate. (node_modules/express/lib/router/index.js:618:14) This pertains to both server and test files. // server js file 'use strict& ...

Harness the power of the Node.js Path module in conjunction with Angular 6

I'm currently facing an issue with utilizing the Path module in my Angular 6 project. After some research, I came across a helpful post detailing a potential solution: https://gist.github.com/niespodd/1fa82da6f8c901d1c33d2fcbb762947d The remedy inv ...

Halt the foreach iteration until the request is fully processed and the result is returned

I have a scenario where I am retrieving data from my Azure mobile service database. In the read script, I am attempting to modify the response by utilizing the tracking number in the results to make use of a node module called "ups_node". I am adding a s ...

Issue: ENOENT encountered with __dirname usage

When building my website using Express, I encountered an issue with my code in server.js: app.use(express.static('public')); app.get('/add', function (req, res) { res.sendFile(__dirname + "/" + "add.htm");}) The structure of my projec ...

You cannot use voice_channel.join() to create a music bot in discord.js v13

As I was working on a new music command feature for my Discord bot, I encountered an issue. Whenever I try to use the command -play {url}, I keep getting an error message that says: voice_channel.join is not a function. I searched through various resource ...

Coordinating multiple API requests for optimal performance

I have a task where I need to retrieve data from two different API endpoints. Once both sets of data are fetched, I need to compare the information obtained from each source. I am familiar with fetching data from a single API endpoint and using a callback ...

What is the best way to combine a React App and an Express App in order to deploy them as one

After successfully creating an Express and MongoDB API and connecting it to my React Application, I encountered a situation during deployment. It seems that I need to deploy both projects separately, which means I would need two hosting plans for them. H ...

Express causing textarea in http form to have empty req.body

Here is a form for users to upload a file and submit text: form(action='/createpost' enctype="multipart/form-data" method='post' id="imgForm") input(type='file' name='imgPath' size = "60") br textarea(na ...

Having issues loading the GoCardless SDK through the require function

Every time I attempt to load the GoCardless SDK and apply the configuration as outlined in the documentation, Node.js throws the following error: var gocardless = require('gocardless')(gcConfig); ^ TypeError: r ...

Setting up a hostname for the next/image component

Recently, I attempted to enhance my NextJS application by implementing <Image /> from next/image. The images I am using are stored remotely. To make remote images functional, it appears that I need to include my domain in the next.config.js. Below i ...

Unable to generate an index with mongoose

I'm currently working on developing a search functionality within my Node.js application that utilizes Mongoose, aiming to create a full-text search index in Mongo: postSchema = mongoose.Schema({ xx : String ....... }).index({ ...

Encountering Axios errors while executing API calls at a high frequency

Recently, I have been facing some challenges with making API calls from localhost using axios in a loop. While it works smoothly at times, most often I encounter errors like: cause: Error: connect ECONNREFUSED ::1:8000 at TCPConnectWrap.afterConnect ...

Is there a way to determine whether all fields in a schema have been populated or remain empty?

I am working with a schema that looks like this: How can I determine if all the fields in the schema have been filled or not? The front-end (React.js) includes an onboarding process where users who are logging in for the first time need to complete onboa ...

Error message encountered in MEAN application request

Learning how to use the MEAN stack has been an exciting journey for me as I venture into building web apps. Rather than relying on yeoman generators or npm app to do the heavy lifting of generating code, I have delved into creating my entire app from scrat ...

Quick Serve - Open to the World

Utilize Ubuntu I currently have an Express app set up with a simple Hello world message. My goal is to make this app accessible to the public by setting up a static IP address, similar to what's demonstrated in this video. Below is my code for the ex ...

`Resolving issue with "exports" not being defined when running my Node.js project

Out of nowhere, I encountered an issue while trying to run npm start on my project. To my surprise, it displayed the following errors: https://i.stack.imgur.com/mWRI9.png ...

"NodeJS application interfacing with Elasticsearch utilizes promise-based search function instead of direct

Within my Node server, I have successfully made a request to Elasticsearch. However, I am encountering an issue where instead of the actual results, I always receive a promise. Although the results display perfectly when logged in the console, they either ...

Using the combination of Node.js, ZeroMQ, and Socket.io, we can implement scoping per

I am currently in the process of developing a web application using node.js and express to deliver a real-time aprs stream to each user through ZeroMQ and socket.io. The idea behind it is that the node.js app receives the complete aprs stream by subscribi ...

I encountered a 404 Error message while attempting to access a specific express route

My Angular CLI generated app is running with an Express.js and MongoDB server. After running npm start, I can access http://localhost:3000, which routes to my homepage. The other links on the navbar work well to control routes, e.g., http://localhost:3000/ ...

Utilizing nested grouping in mongoose schemas

I am facing a challenge while attempting to execute a nested group query in MongoDB. Is there a way to group data by both date and campaign ID, ensuring that each campaign ID contains a nested array of creatives with their respective data (views and clicks ...