簡體   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