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

Invoke `setState` function in contexts outside of React framework

Is the following approach guaranteed to work correctly within React v18 semantics? The "rules of hooks" only address calling the hook within the component, with no mention of whether it's acceptable to call the dispatcher returned from the ...

What steps are involved in setting up a point distribution system in AngularJS?

My objective is to develop a point allocation system within AngularJS. I have successfully created a basic directive that introduces DOM elements, including a span displaying "0" points and buttons for incrementing and decrementing. The total number of poi ...

Transforming React-Leaflet Popup into a custom component: A step-by-step guide

Currently working on a project where I am utilizing both React-Leaflet and Material-UI by callemall. The challenge I am facing involves trying to incorporate the Material-UI Card component within the <Popup></Popup> component of React-Leaflet. ...

Modifying button styles in Angular UI Datepicker

In this plunk, there is an Angular UI Datepicker with a template. I'm trying to customize the colors of the "Today", "Clear", and "Close" buttons by editing the popup.html. However, even after changing the classes in the code, the datepicker still sho ...

Switch off any other currently open divs

I'm currently exploring a way to automatically close other div's when I expand one. Check out my code snippet below: $( document ).ready(function() { $( ".faq-question" ).click(function() { $(this).toggleClass('open'); $(this ...

How can you access additional fields beyond what is displayed in a dropdown select menu in React?

I am working with an array of Jsons that contain the fields ID, name, and description. My goal is to create a dropdown selection box that will show both the name and description when clicked, and then store the associated ID in the rawID state. I have been ...

Transmitting a JavaScript file via a Node.js server

I have a NodeJS server that sends a JavaScript file to the client. However, the JavaScript file does not import the libraries it needs on the client side. I load these libraries on the client side before receiving the file. Why is the file unable to find t ...

How to position items at specific coordinates in a dropdown using JavaScript

I have five images in my code and I would like to arrange them in a circular pattern when they are dropped into the designated area. For example, instead of lining up the five images in a straight line, I want them to form a circle shape once dropped. Ho ...

Incorporating an external library into a Node.js virtual machine

I'm currently working on a nodejs library that enables users to write and execute their own JS code. Here is an example: var MyJournal = Yurnell.newJournal(); module.exports = function(deployer) { MyJournal.description = "my first description& ...

Why is it necessary in JavaScript to reset the function's prototype after resetting the function prototype constructor as well?

Code is often written in the following manner: function G() {}; var item = {...} G.prototype = item; G.prototype.constructor = G // What is the purpose of this line? Why do we need to include G.prototype = item before resetting the prototype? What exact ...

Best practices for working with HTML elements using JavaScript

What is the best approach for manipulating HTML controls? One way is to create HTML elements dynamically: var select = document.getElementById("MyList"); var options = ["1", "2", "3", "4", "5"]; for (var i = 0; i < options.length; i++) { var opt = ...

Using ReactJS to pass an onClick event to a different component

Is there a way to implement the onClick event on an anchor tag to update state in another component? Utilizing onClick in Card.js Component import React from 'react' import PropertyLightbox from '../global/PropertyLightbox' const Car ...

"Encountering an issue while installing Express with the Node Package Manager

While trying to install express using the node package manager on my Windows 7 x64 machine, I encountered the following error. I am running cmd as an administrator. Can anyone provide assistance? Microsoft Windows [Version 6.1.7601] Copyright (c) 2009 Mic ...

What is the best way to initiate a re-render after updating state within useEffect()?

I'm currently strategizing the structure of my code using React hooks in the following manner: Implementing a state variable to indicate whether my app is loading results or not The loading state turns to true when useEffect() executes to retrieve da ...

Performing multiple ajax calls simultaneously in JavaScript using the React framework

Within my React application, I am faced with the challenge of handling an array of parameters (such as IDs) that need to be passed as parameters in a queue of ajax calls. The issue arises when this array exceeds 1000 items, causing the browser page to beco ...

Tips for creating a useState variable within the render() function in reactjs

I'm completely new to reactjs, and I've been trying to define useState variables within the render() method of a reactjs component. However, I keep running into an error: "Invalid hook call." class ProductDefinition extends Component { construc ...

Vue.js computed property experiencing a minor setback

I'm currently working on developing a test-taking system using Vue and Laravel. When a user inputs the test code and email address, they are directed to the test page. To display all the test questions based on the entered code, I implemented a naviga ...

Synchronization issue between CSS style and Javascript is causing discrepancies

I am looking to avoid using jquery for simplicity. I have three websites that each page cycles through. My goal is to scale the webpages by different values. I attempted applying a class to each page and used a switch statement to zoom 2x on Google, 4x o ...

Learn how to implement validation middleware in NodeJs/Express

I have a main file named index.js where I load some content and then branch out to different files for my routes. My concern is about the app.use function that checks for a valid token, as I have multiple instances of this in my code. app.use(function(req ...

What is the method to retrieve JSON data from a URL and showcase the content on a JavaScript page?

I am currently developing a custom MS Teams application and I am facing an issue with fetching JSON data from a URL to display its contents later. Unfortunately, the fetch operation is failing. My objective is to retrieve a list of data from a specified UR ...