Ways of transferring session variables from one page to another?

Initially, I am working with multiple webpages in express. After saving a variable into a session during a post request, the page redirects to another page. However, when trying to access the variable on that new page, it is returned as "Undefined." Upon further investigation, I noticed that the session ids in those two functions do not match up. This discrepancy might be due to the sessions being local.

I was anticipating the secure passing of the variable between the two functions without the need for a database since all variables are temporary.

Answer №1

A common illustration of setting up sessions in Express is provided below. Feel free to customize the code based on your specific requirements.

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

const app = express();

app.use(session({
    secret: 'your_secret_key', // Replace with a secure secret key
    resave: false,             // Prevents session from being saved if not modified
    saveUninitialized: true,   // Allows saving new sessions even if they are not modified
    cookie: { secure: false }  // Use true for HTTPS environment
}));

app.use(express.json());       // For handling JSON data
app.use(express.urlencoded({ extended: true })); // For parsing URL-encoded data

const PORT = 8080;

// Route to store data in session and redirect
app.post('/save-to-session', (req, res) => {
    const { myVariable } = req.body;
    req.session.myVariable = myVariable;
    res.redirect('/next-page');
});

// Route to retrieve data from session
app.get('/next-page', (req, res) => {
    const myVariable = req.session.myVariable;
    if (myVariable) {
        res.send(`The variable stored in session is: ${myVariable}`);
    } else {
        res.send('Variable not found in session');
    }
});

app.listen(PORT, () => {
    console.log(`Server is running at http://localhost:${PORT}`);
});

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

Routing WebSocket connections with Node.js

Currently, I am in the process of developing a chat application for my company which will run on node js with websocket (ws). The app is designed to cater to various departments within the organization, each with its own set of users. My goal is to ensure ...

What is the best way to display multiple .ejs files in a nested structure using Node.js and Express?

Is there a way to display multiple .ejs files in a nested structure? Consider the code snippet below: var mysql = require('mysql'); var ejs = require('ejs'); exports.index = function(req, res){ if (req.method=='POST'){ ...

Cannot use MaterialUI Textfield/Input on iPhone devices

Recently, I encountered an issue with iPhone users being unable to type in Textfield or Input components in apps developed using MaterialUI, even when the value and setValue were properly configured. To solve this problem for each component individually, ...

Utilizing v-model dynamically to showcase the outcomes of a specific property within a v-for iteration

As I iterate over an array using v-for, the number of items in this array varies each time. Currently, I am able to input values into the fields and have them correctly update the data property associated with them. However, there are two issues that need ...

What is the best way to showcase the outcomes of a map function in JSX?

I'm currently learning react and working on implementing the searchMap function (to display movie title/poster) with the TMDB API. While I am able to successfully log the necessary information to the console, I am encountering issues such as undefined ...

SyntaxError was not caught and an unexpected token export occurred at line 2371 in the popper.js file

I'm a beginner with bootstrap and jquery, and I'm attempting to utilize the datatables feature for sorting. However, when I run my code, I encounter the following error in the console: uncaught SyntaxError: Unexpected token export at popper.js:2 ...

Struggling to launch the Node.js server on the OpenShift platform

Check out this snippet of code: var express = require('express'); var net = require('net'); var app = express(); var sock; //Establishing connection with mobile server on port 5132 console.log('Waiting for connection\nfrom ...

Express not invoking Passport LocalStrategy

I added a console.log statement in the LocalStrategy callback of passport.js, but it never seemed to execute. I am using Sequelize for ORM with MySQL. passport.js const LocalStrategy = require('passport-local').Strategy const passport = require( ...

Angular's method of one-way binding to an object

Seeking a method for one-way (not one time) binding between an attribute on a directive without utilizing attrs.$observe. Currently considering binding via &attr and invoking the variables in the template like {{attr()}}. app.controller('MainCtrl ...

The custom directive in Vue utilizes the refreshed DOM element (also known as $el)

I am looking to create a custom directive that will replace all occurrences of 'cx' with <strong>cx</strong> in the Dom Tree. Here is my current approach: Vue.config.productionTip = false function removeKeywords(el, keyword){ i ...

Converting an ajax request to CORS

Would appreciate some guidance on accessing an API through my localhost using the code below: $.ajax({ url: "http://domain.xxx.net/api/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d7a3b8bcb2b9a4f9bda4b8b9e8b2ba ...

"Rearranging the Firefox ghost image by dragging and dropping it

My drag and drop game is working perfectly on all browsers except for Firefox. In Firefox, the ghost image that appears when an item is dragged seems to be positioned very far away from the cursor. Although the ghost image can still be seen on the page, it ...

Switching Over to Burger Menu

I created a burger menu using HTML, CSS, and jQuery that switches from a full-width menu to a burger menu. However, I'm facing an issue with toggling the dropdown when the menu collapses. Here's my code: <!DOCTYPE html> <html> < ...

Mapping JSON data with an elastic search cluster can be challenging, especially when dealing with a dynamic number of fields

I am currently developing an application where I need to map JSON data for storage in Elasticsearch. The challenge is that the number of fields in the JSON data is dynamic. How can I handle mapping in this scenario? Mapping Snippet var fs = uploadedFiles ...

The embedded iframe on YouTube is displaying the incorrect video

I am currently designing a website and I want to feature a video on the homepage. The video is hosted on YouTube and I need to embed it into my website. <html> <iframe width="560" height="315" src="https://www.youtube.com/embed/spPdelVEs_k?rel= ...

Comparing JSON and JavaScript object arrays: Exploring the differences in outcomes and strategies for achieving desired results

Although it's not valid JSON, I've found that by declaring this as a variable directly in my code, I can treat it like an object. <script> // this will result in object var mydata = { users: [{ person: { ...

Unable to locate the module 'winston'

Developed a small module that utilizes winston for logging purposes. Installed winston using sudo npm install -g winston (since it's on a virtual machine, not too concerned with sudo permissions). NPM log: <a href="/cdn-cgi/l/email-protection" c ...

The Discord.js collector seems to have no intention of ending, completely disregarding its keys in order

Help Needed with Discord Message Collector Issue I encountered a problem with my code that assigns ranks on Discord. It seems that the message collector is not responding to keys that should stop it from collecting messages. Can anyone offer assistance in ...

Having issues with the custom listing feature in Jquery UI auto complete not functioning as expected

I am facing an issue with my implementation of jquery UI autocomplete. The autocomplete functionality is not working as expected, despite the absence of any JavaScript errors. Below is the JSON data that I am working with: {"d":"[{\"label\":&bs ...

jQuery Filter for Page Content - choose specific text within paragraphs and clickable links

I recently created a page search filter using Bootstrap 5, but it seems to only display text content and not any content enclosed within the a tags. You can check out the JS Fiddle link provided below for reference: https://jsfiddle.net/mfen723/rozy16pt/1 ...