Access the session on both routers

I currently have 2 different routers set up in my application:

Router 1

app.post('/consultations', function(req, res) {

    req.session.name = 'administrator';
   console.log('test', req.session.name); // the session is properly saved here
});

Router 2

router.get('/', function(req, res) {
    console.log('retrieve session', req.session); // returns undefined
}

I am wondering how I can access and retrieve the session data from both routers.

EDIT: I have created a middleware for this purpose

function mymiddleware(req, res, next) {
  req.session.name = 'MyNAME';
}

When I try to utilize the middleware on each router route:

app.get('/myroute1', mymiddleware, (req, res) => {
      console.log(req.session.name);
}

The output never gets logged. Similarly,

app.get('/myroute2', mymiddleware, (req, res) => {
          console.log(req.session.name);
}

Answer №1

const myMiddleware = (req, res, next) => {
  req.session.name = 'MyName';
  next();
}

The next() function will invoke the next middleware in line, which is:

(req, res) => {
      console.log(req.session.name);
}

Answer №2

I believe that in your middleware, it is necessary to invoke the next() function

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

Issues with displaying AJAX Bootstrap Modals

I'm struggling to display a Bootstrap modal with dynamically generated content from the database. The data is not showing up in the modal body, and I've been troubleshooting this issue for quite some time now. Modal <div class="modal fade" i ...

Are there any available npm modules for accurately tallying the total word count within a document saved in the .doc or .doc

I Need to tally the number of words in doc/docx files stored on a server using express.js. Can anyone recommend a good package for this task? ...

Mocking objects in unit test cases to simulate real-life scenarios and test the

How do I pass a mocked event object and ensure it is validated? onCallFunction() { const eventValue = event; if (!eventValue.relatedTarget || !eventValue.relatedTarget.last.contain('value')) { super.onCallFuncti ...

Modify the NAME attribute when clicked using Jquery

I am attempting to modify the NAME attribute of a DIV with the text from a textbox using jQuery. Take a look at my code snippet: http://jsfiddle.net/e6kCH/ Can anyone help me troubleshoot this issue? ...

Tips for managing both DOM manipulation and state changes at the same time in AngularJS

<div my-custom-directive> <button id="myButton" ng-click="handleClick(mymodel.id)"><button> </div> app.controller('myCtrl', function($scope) { $scope.handleClick = function(id) { //Perform state change here without ...

`Obtaining an array of selected values from a deeply nested JSON object`

Looking to extract specific key values from a nested JSON object based on the boolean value of another key. In this case, I need the "name" key values for items where the "checked" key is true, and return them in a result array. Here is an example of the ...

Displaying data stored in a database using JSON format with Ember

I seem to be facing a challenge once again. Let me elaborate on what I am trying to achieve. Within the teammembers template, I aim to display information about Team Members and their details from a specific team by joining 3 tables. Here is an example o ...

How can one properly iterate through an HTML Collection in JavaScript?

I need help with creating a slider using JavaScript. The code I have written below calculates the widths of the slides, but it's throwing an error in the console. Can someone advise on how to properly loop through and assign width to these elements? ...

How can we fetch data from the server in Vue 2.0 before the component is actually mounted?

Can anyone help me with this question noted in the title? How can I prevent a component from mounting in <router-view> until it receives data from the server, or how can I fetch the data before the component is mounted in <router-view>? Here a ...

Using "sequelize freezeTableName" while still preserving the plural form of the table name in the

I am currently using express+ionic+mysql+sequelize for building an application and encountering an error in the sequelize framework. There are three tables involved: xx_product xx_product_specification_value xx_specification_value The relation ...

Function to directly download an image to S3 - retrieve the data key

I've been wracking my brain over this issue for a couple of days now. The function below is functional; it takes a URL and uploads the file to S3. However, I'm struggling with getting the file location on S3 (data.key) returned outside of the ma ...

Errors encountered when using Puppeteer on Kubernetes: "Detached navigation frame" and "Attempting to access main frame too soon"

I have been attempting to execute a nodejs based Docker container on a k8s cluster, but I am encountering persistent errors: Navigation frame was detached Requesting main frame too early In an effort to resolve this issue, I have condensed the code to ...

What is the best way to obtain the ID following a fetch request?

I'm trying to target the ID specifically, but when I console log the data retrieved after making a fetch request, it contains more information than just the ID. I want to know how to extract and print only the ID from the response in the console. fetc ...

The error message UnhandledPromiseRejectionWarning is triggered due to a TypeError stating that the function authenticate is

Currently, I am attempting to incorporate basic authentication into my API project using Knex, Express, and MySQL. Here are the functions I have implemented: const users = [{ id:1, username:'selia', password:'fullservice'}] functio ...

Leveraging Angular 2 and RxJs 5 beta observables to continuously stream data from a while loop

I am looking to develop a straightforward Angular 2 application that calculates prime numbers within a while loop and continuously updates the view with newly discovered values. My goal is to showcase the list of prime numbers using *ngFor in real-time, gi ...

Guide to using Ajax to send a form and receive text in response

Check out my code on Fiddle: $("form.signupform").submit(function(e) { e.preventDefault(); var data = $(this).serialize(); var url = $(this).attr("action"); var form = $(this); // Added this line for reference $.post(url, data, function(data) { $(for ...

What's the proper way to mention HTML React component classes without triggering their execution?

When working with HTML React components like div, a, p, li, we typically write them in JSX syntax: <div>Hello</div> However, how can we reference one of these components without actually "using" them? For custom components, we can import, ref ...

Enhance an existing webpage by integrating ajax with jquery-ui

I'm seeking assistance with integrating an advanced search feature into an existing webpage system. It appears that there is a complication with the current jQuery UI being used on the page: <script src="js/jquery-ui-1.10.4.custom.js"> ...

Having trouble accessing static files with express? If you see the message "Cannot Get /", this might be the

After trying to learn how to read static files with Express from a reliable website, I encountered an issue. My terminal indicated that the operation was successful, but when I checked the website, it displayed "Cannot Get /" (as shown in the image). Despi ...

Encountering an npm issue while attempting to execute the command "npx create-expo-app expoApp"

I've been attempting to set up an expo project, but npm is failing to do so. It does create necessary base files like APP.js, but nothing else. Here's the error I encountered: npm ERR! code ENOENT npm ERR! syscall lstat npm ERR! path C:\User ...