[英]Express.js passing variable in dynamically created route
I am creating routes in express js from json file with following structure 我正在使用以下结构从json文件在express js中创建路由
{
"/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 我用来生成路由的js是
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. 我面临的问题是route-mixin方法始终获取最后一个令牌。 context
in this case is just the js file i added above. 在这种情况下, context
只是我上面添加的js文件。 How can i pass different tokens for each route individually. 如何分别为每个路由传递不同的令牌。
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: 首先让我知道问题出在哪里的是PhpStorm IDE:
The error message mutable variable is accessible from closure
appeared within the first middleware. 错误消息mutable variable is accessible from closure
出现在第一个中间件中的mutable variable is accessible from closure
。 This article Mutable variable is accessible from closure. 可以从闭包访问本文的Mutable变量。 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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.