Passing variables dynamically in a created Express.js route

Creating routes in Express.js from a JSON file with the specified structure:

{
  "/home":{
    "token":"ksdjfglkas"
  },
  "/logout":{
    "token":"ksdjfglksaudhf"
  }
}

It is necessary to access the token within the routes function. The JavaScript code used for generating the route is as follows:

for(var endpoint in context){
  var route = context[endpoint];
  app.use(endpoint,
    function(req,res,next){
      req.token= route.token;
      next();
    },
    require('./route-mixin'));
}

The issue encountered is that the route-mixin method always receives the last token. In this case, 'context' refers to the JavaScript file mentioned above. How can different tokens be passed for each route individually.

Answer №1

To solve this issue, I implemented a closure to encapsulate the content within the loop.

The problem was initially identified thanks to PhpStorm IDE: https://i.stack.imgur.com/4fQWz.png

Encountering the error message

mutable variable is accessible from closure
in the first middleware led me to seek guidance from this article Mutable variable is accessible from closure. How can I fix this?, suggesting the use of closures.

The simple resolution involved changing the code snippet from:

   for(var endpoint in context){
         var route = context[endpoint];
         app.use(endpoint,
             function (req, res, next) {
                 req.token = route.token;
                 next();
             },
             function (req, res) {
                 console.log(req.token);
                 res.send('test');
             }
         );
    }

to:

for(var endpoint in context){
    (function() {
        var route = context[endpoint];
        app.use(endpoint,
            function (req, res, next) {
                req.token = route.token;
                next();
            },
            function (req, res) {
                console.log(req.token);
                res.send('test');
            }
        );
    })();
}

The final example below demonstrates the functional solution that allowed the code to run successfully:

var express = require('express');
var app = express();

var context =  {
    "/home":{
        "token":"ksdjfglkas"
    },
    "/logout":{
        "token":"ksdjfglksaudhf"
    }
};
for(var endpoint in context){
    (function() {
        var route = context[endpoint];
        app.use(endpoint,
            function (req, res, next) {
                req.token = route.token;
                next();
            },
            function (req, res) {
                console.log(req.token);
                res.send('test');
            }
        );
    })();
}

app.listen(3000);

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

Utilize the datepicker function in jQuery version 1.6.3 to select a range of dates

I need help adding a jQuery datepicker to my JSP page for selecting a date range. Below is the current code I am working with. $(function() { $( "#createdAtFrom" ).datepicker({ defaultDate: "+1w", changeMonth: true, ...

Configure webpack to source the JavaScript file locally instead of fetching it through HTTP

Using webpack.config.js to fetch remote js for Module Federation. plugins: [ new ModuleFederationPlugin({ remotes: { 'mfe1': "mfe1@http://xxxxxxxxxx.com/remoteEntry.js" } }) ], Is it possible to incorporate a local JS ...

Slider with Dual Images: A Visual Comparison

I'm currently working on a webpage that features before and after images using a slider based on mouse movement to display both pictures. I am trying to incorporate multiple sliders on the same page but have been facing difficulties in getting them to ...

HapiJS commences an extended duration background process

Is there a way to achieve the functionality of a PHP exec function in HapiJS? I have a scenario where the user submits a processing job that requires running in the background for a significant amount of time. An essential requirement is to provide the us ...

In node.js, ensure that only JSON error messages are sent instead of HTML

When a user registers in the app with incorrect details such as phone number or email, I intend to throw an error as a JSON object. However, the postman response is displaying HTML. The registration route: exports.register = async (req, res) => { try ...

The hosting service Heroku is currently having trouble recognizing the concurrent command within the "npm run start" script

This is an inquiry posted on Stack Overflow: My hosting provider, Heroku, does not seem to recognize the "concurrently" command in my "npm run start" script. I can successfully run this command locally using "heroku local web" but encounter log errors whe ...

Using Typescript in React to render font colors with specific styling

Attempting to utilize a variable to set the font color within a react component, encountering an error with my <span>: Type '{ style: "color:yellow"; }' is not assignable to type 'HTMLProps<HTMLSpanElement>' The use of yel ...

The Safari 7.1+ browser seems to be having trouble with the spotlight effect

Why is the CodePen not functioning properly in Safari? Despite working well in Chrome and Firefox, it completely fails to work in Safari 7.1+. Can anyone provide some insights? http://codepen.io/cchambers/pen/Dyldj $(document).on("mousemove", function( ...

Acquire the content of a nested element using jQuery

I have a navigation list with separate headlines and text for each item. The goal is to switch the main headline and paragraph of text when hovering over a navigation item. CodePen Example Currently, my code displays all text. I only want to display the ...

Mastering the art of grouping by a key and generating sub-objects from a plain array of key-value pairs in JavaScript ES5 without relying on third-party libraries

My dataset consists of an array of objects, each containing 4 keys: [ { "team": "USA", "team_profile_id": "10", "player": "Captain America", "player_id": "10X1" }, { "team": "USA", "team_profile_id": "10", "player": "The ...

Executing Code Upon Module Load and Presenting It as Middleware

I am currently delving into the intricacies of how exporting and importing modules function in Nodejs. One of my tasks involves using a specific file to seed a mongodb database. Surprisingly, this file operates flawlessly and delivers the desired results ...

How do I test Pinia by calling one method that in turn calls another method, and checking how many times it has been called

As I embark on my journey with Vue 3 and Pinia, a particular question has been lingering in my mind without a concrete answer thus far. Let's delve into the crux of the matter... Here's an example of the store I am working with: import { ref, co ...

Encountering a problem when trying to reference socket.io

I've been working on building an express app with chat functionality, but I've run into an issue with socket.io. It's not working properly and is throwing an "uncaught reference" error when I try to run the server. You can see a screenshot o ...

Comparing Server Sent Events and Ajax with Websockets and Ajax

I am currently developing an application using Nuxt.js and facing challenges in determining the best approach for sending data to the API built with Express.js and receiving real-time updates. I have identified that "bi-di" connections can be established u ...

Exploring the Art of Navigation with Ionic and Angular

Trying to integrate Angular, Meteorjs, and Ionic Framework has been a smooth process, thanks to the urigo:angular and urigo:ionic packages. However, I'm facing difficulties in configuring ionic links and angular routing to make it work seamlessly. Des ...

What is the best way to adjust the width of these elements for a perfect fit?

I'm currently working on a website where I have arranged squares in a grid layout. My goal is to make these squares perfect, with equal width and height. The only issue I'm encountering is that they tend to change between fitting two and three sq ...

Execute sequential animations on numerous elements without using timeouts

I'm currently working on developing a code learning application that allows users to write code for creating games and animations, similar to scratch but not block-based. I've provided users with a set of commands that they can use in any order t ...

Learn how to easily toggle table column text visibility with a simple click

I have a working Angular 9 application where I've implemented a custom table to showcase the data. Upon clicking on a column, it triggers a custom modal dialog. The unique feature of my setup is that multiple dialog modals can be opened simultaneously ...

Simple steps to add a click event listener to every element within a div

I need to assign a click handler to multiple elements and perform different actions based on which one is clicked. To illustrate, I can create an alert displaying the class of the button that was clicked. The elements I am working with have a similar str ...

Prevent accordion expansion triggered by the More button click

When the More button is clicked, it should NOT expand and collapse. https://i.sstatic.net/toV1b.gif If the accordion initial state is open, it must stay open even if button is clicked, if initial state is collapsed then after the more button the accordio ...