繁体   English   中英

Express.js在动态创建的路由中传递变量

[英]Express.js passing variable in dynamically created route

我正在使用以下结构从json文件在express js中创建路由

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

我需要能够访问路由功能内的令牌。 我用来生成路由的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'));
}

我面临的问题是route-mixin方法始终获取最后一个令牌。 在这种情况下, context只是我上面添加的js文件。 如何分别为每个路由传递不同的令牌。

解决此问题的方法是将循环内的内容放入闭包中。

首先让我知道问题出在哪里的是PhpStorm IDE: 可从闭包访问可变变量

错误消息mutable variable is accessible from closure出现在第一个中间件中的mutable variable is accessible from closure 可以从闭包访问本文的Mutable变量。 我怎样才能解决这个问题? 然后给了我使用闭包的提示。

因此,使它运行所需的一切都在变化:

   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');
             }
         );
    }

至:

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');
            }
        );
    })();
}

我成功运行的完整示例代码:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM