Reputation: 3617
I am creating routes in express js from json file with following structure
{
"/home":{
"token":"ksdjfglkas"
},
"/logout":{
"token":"ksdjfglksaudhf"
}
}
I need to be able to access the token inside the routes function. The js that i am using for generating the route is
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 problem that i am facing is that route-mixin method always gets the last token.context
in this case is just the js file i added above. How can i pass different tokens for each route individually.
Upvotes: 0
Views: 258
Reputation: 3487
The solution to this problem is to put the content within the loop into a closure.
What gave me the idea what's the issue in the first place, was the PhpStorm IDE:
The error message mutable variable is accessible from closure
appeared within the first middleware. This article Mutable variable is accessible from closure. How can I fix this? gave me then the hint to use a closure.
So all what was necessary to get it running was changing:
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 full example code I was successfully running:
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);
Upvotes: 1