【问题标题】:How to pass data between routes in express.js如何在 express.js 中的路由之间传递数据
【发布时间】:2020-08-30 02:09:55
【问题描述】:

希望有人可以帮助我。找不到解决办法。也许我也只是走错路了? 这是一个简单的快速设置,我很新。 我从请求中得到响应,并希望将响应中的变量/数据传递到下一个路由到 URL。 因此,根据第一次调用的响应,下一个 URL 中的一个参数应该是动态的。

这里是我的全部代码:

我的问题是你可以在哪里看到 const sendoutID

const express = require("express");
const app = express();
const request = require("request");
const bodyParser = require("body-parser");
const port = 3001;

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));




// Create Sendout
app.post("/createSendout", (req, res, next) => {
  request.post(
    {
      url: "https://www.something.com/api/v1.2/surveys/904211/sendouts",
      body: JSON.stringify(req.body),
      headers: {
        "Content-Type": "application/json",
        "X-API-KEY": "xxxx-xxx-xxxx-xxx-xxxxxxx",
      },
    },
    function (error, response, body) {
      console.log(response.statusCode);
      if (!error && response.statusCode == 200) {
        // Successful call
        var results = JSON.parse(body);
        console.log(results.CreateSendoutResult.SendoutId); // View Results

// I want this data "results.CreateSendoutResult.SendoutId" passing to the next route

       
      }
    }
  );
});


/* here the variable is just hard coded for now but 
I want to pass it in the URL from my previous route 
to the next route see below at + sendoutID +..*/

const sendoutId = 389125;


// Add Respondent
app.post("/addRespondent", (req, res, next) => {
  request.post(
    {
      url:
        "https://www.something.com/api/v1.2/surveys/904211/sendouts/" +
        sendoutId +
        "/respondents",
      body: JSON.stringify(req.body),
      headers: {
        "Content-Type": "application/json",
        "X-API-KEY": "xxxxxx-xxx-xxx-xxx-xxxxxxxx",
      },
    },
    function (error, response, body) {
      console.log(response);
      //console.log(response.statusCode);
      if (!error && response.statusCode == 200) {
        // Successful call
        var results = JSON.parse(body);
        console.log(results); // View Results
      }
    }
  );
});


app.listen(port, () => {
  console.log(`app listening at http://localhost:${port}`);
});


【问题讨论】:

    标签: node.js express


    【解决方案1】:
    1. 要传递到下一条路线,您可以将results.CreateSendoutResult.SendoutId 分配给req.body

      req.body.SendoutId = results.CreateSendoutResult.SendoutId;

    然后你可以在下一个路由中使用该 SendoutId。

    1. 您可以在 next() 中传递该变量

      下一个(results.CreateSendoutResult.SendoutId);

    在下一条路线中,您可以通过调用来访问它:

    function nextRoute(SenderId, req, res, next)
    

    已编辑:

    const express = require("express");
    const app = express();
    const request = require("request");
    const bodyParser = require("body-parser");
    const port = 3001;
    
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({ extended: true }));
    
    
    
    
    // Create Sendout
    app.post("/createSendout", (req, res, next) => {
      request.post(
        {
          url: "https://www.something.com/api/v1.2/surveys/904211/sendouts",
          body: JSON.stringify(req.body),
          headers: {
            "Content-Type": "application/json",
            "X-API-KEY": "xxxx-xxx-xxxx-xxx-xxxxxxx",
          },
        },
        function (error, response, body) {
          console.log(response.statusCode);
          if (!error && response.statusCode == 200) {
            // Successful call
            var results = JSON.parse(body);
            console.log(results.CreateSendoutResult.SendoutId); // View Results
    
    // I want this data "results.CreateSendoutResult.SendoutId" passing to the next route
    
          req.SendoutId = results.CreateSendoutResult.SendoutId;
           
          }
        }
      );
    }, addRespondent);
    
    
    /* here the variable is just hard coded for now but 
    I want to pass it in the URL from my previous route 
    to the next route see below at + sendoutID +..*/
    
    const sendoutId = 389125;
    
    
    // Add Respondent
    app.post("/addRespondent", addRespondent);
    
    function addRespondent(req, res, next) => {
      request.post(
        {
          url:
            "https://www.something.com/api/v1.2/surveys/904211/sendouts/" +
            req.sendoutId +
            "/respondents",
          body: JSON.stringify(req.body),
          headers: {
            "Content-Type": "application/json",
            "X-API-KEY": "xxxxxx-xxx-xxx-xxx-xxxxxxxx",
          },
        },
        function (error, response, body) {
          console.log(response);
          //console.log(response.statusCode);
          if (!error && response.statusCode == 200) {
            // Successful call
            var results = JSON.parse(body);
            console.log(results); // View Results
          }
        }
      );
    }
    
    
    app.listen(port, () => {
      console.log(`app listening at http://localhost:${port}`);
    });
    
    
    

    【讨论】:

    • 感谢您的快速回答!我尝试了您的建议,但似乎我仍然做错了什么。您能否将其添加到我的代码中,以便我可以仔细检查是否在正确的位置添加了所有内容?
    • 您提到我希望将此数据“results.CreateSendoutResult.SendoutId”传递到下一条路线。你这是什么意思?您希望将响应发送到 Create Sendout 路由吗?
    • 我从第一个路由器的端点得到响应。在这个响应中是一个“sendoutId”。这个“sendoutId”需要是下一个路由器中端点的参数。网址:https://www.something.com/api/v1.2/surveys/904211/sendouts/${sendoutId}/respondents
    • 已更新我的答案希望这能回答您的问题。
    • 谢谢,不幸的是它仍然不起作用。我已经尝试了很多并且changex很多。检查每个变量是否正确写入..但它仍然无法识别 id。它显示在我的控制台中,它是正确的,我肯定知道,但它没有在 URL 中添加 id 作为参数
    【解决方案2】:
    1. 您应该使用中间件函数。

    什么是中间件函数?

    -> 它只是一个在中间运行的函数,即(在请求到达路由之前并在请求完成之前结束。Express Documentation for writing middlewares.

    中间件函数是可以访问请求对象 (req)、响应对象 (res) 和下一个函数的函数。注意中间件函数不会结束请求-响应循环,它必须调用 next() 将控制权传递给下一个中间件函数。否则,请求将被挂起。

    使用中间件功能的优势 ->“您以后也可以将此功能用于任何其他请求”,在其他模块中使用它。

    2)

    const captureSendOutIDMiddleware = async (req, res, next) => {
        try {
             req.SendOutID=results.CreateSendoutResult.SendoutId; //changed "const req" to just req.
                 next();
    
        } catch (error) {
            res.status(401).send({
                error: 'NO SEND OUT ID'
            })
        }
    app.post("/CreateSendOut",captureSendOutIDMIddleware,async(req, res) =>{
    //do your operation
    
    });
    
    app.post("/addRespondent",async(req,res)=>{
    
    const capturedSendoutID=req.SendoutID;
    console.log(capturedSendoutID);
    //do you operations
    
    });
    

    【讨论】:

    • 谢谢,我尝试了您的解决方案,但到目前为止还没有成功。但感谢中间件的提示。我需要对此进行更深入的了解。
    • 我在 try 语句中添加了一个更正,(将 const req 更改为 req=..)。为什么我删除,因为 const req 将创建一个新变量,而不是我们想处理相同的请求,所以 req.SendoutID 只会向以前存在的 req 对象添加一个属性。它现在应该可以工作了。
    • 谢谢!我已经尝试过了,但没有奏效。但我发现了另一种解决方案,它在我的第一次测试中有效。也许您的解决方案现在也可以工作,因为我发现了另一个可能也是原因的“问题”。我会将其作为新评论发布。无论如何感谢您的帮助:)
    • 它现在可以工作了,因为之前错误地“const req”语句正在创建一个新变量,但是当我们将其更改为 req.SendOutID=results.CreateSendoutResult.SendoutId;它向现有的 req 对象添加了一个新属性。
    【解决方案3】:

    感谢您的帮助。 我现在找到了另一个解决方案,它和我发现另一个问题一样有效。不知道这是否也是它不起作用的原因,或者您的解决方案不起作用的原因。但我使用 app.set() 和 app.get 来传递数据。 另一个问题是,现在使用 app.set() 和 app.get() 有时可以工作,有时不能。所以我在前端的调用上设置了一个超时,它执行 api 请求。只是之间有一点时间。 这是我的新代码

    // Create Sendout
    app.post("/createSendout", (req, res, next) => {
      request.post(
        {
          url: "https://www.something.com/api/v1.2/surveys/904211/sendouts",
          body: JSON.stringify(req.body),
          headers: {
            "Content-Type": "application/json",
            "X-API-KEY": "xxxxxx-xxx-xx-xxxx-xxxxx",
          },
        },
        function (error, response, body) {
          console.log(response.statusCode);
          if (!error && response.statusCode == 200) {
            // Successful call
            var results = JSON.parse(body);
            console.log(results.CreateSendoutResult.SendoutId); // View Results
            app.set("surveyId", results.CreateSendoutResult.SendoutId);    // new added line
          }
        }
      );
    });
    
    
    // Add Respondent
    app.post("/addRespondent", (req, res, next) => {
      const surveyId = app.get("surveyId");        // new added line
      request.post(
        {
          url:
            "https://www.something.com/api/v1.2/surveys/904211/sendouts/" +
            surveyId +
            "/respondents",
          body: JSON.stringify(req.body),
          headers: {
            "Content-Type": "application/json",
            "X-API-KEY": "xxxxxx-xxx-xxxx-xxxx-xxxxxxxx",
          },
        },
        function (error, response, body) {
          console.log(response);
          //console.log(response.statusCode);
          if (!error && response.statusCode == 200) {
            // Successful call
            var results = JSON.parse(body);
            console.log(results); // View Results
          }
        }
      );
    });
    
    

    【讨论】:

      猜你喜欢
      • 2016-04-20
      • 1970-01-01
      • 1970-01-01
      • 2021-09-12
      • 1970-01-01
      • 2018-09-14
      • 1970-01-01
      • 1970-01-01
      • 2013-09-10
      相关资源
      最近更新 更多