【问题标题】:How to pass a request response to another request?如何将请求响应传递给另一个请求?
【发布时间】:2016-04-22 13:29:39
【问题描述】:

在 ExpressJS 应用程序上使用 request-promise 模块,我想发出两个请求,但我需要将第一个产生的响应数据传递给第二个请求。

我所追求的一个例子是;

const options = {
    url: 'http://api.example.com/v1/token',
    method: 'GET'
};

request(options).then((response) => {
    request({
        url: 'http://api.example.com/v1/user',
        method: 'POST',
        data: { token: response.token } 
    }).then((final_response) => {
        res.send(final_response);
    });
});

我省略了错误处理以保持示例简短。我感兴趣的是一种将响应从一个请求传递到另一个请求的技术。

【问题讨论】:

    标签: javascript node.js http express request


    【解决方案1】:

    您可以通过返回它们来链接承诺。 类似的东西:

    request(options1)
      .then((response1) => {
        return request(options2)
      })
      .then((response2) => {
        return request(options3)
      })
      .then((final_response) => {
        res.send(final_response);
      });
    

    这是一篇关于promise chaining and error handling 的好文章。

    【讨论】:

    • 知道如何将第一个请求的响应传递给第二个请求吗?
    • 您可以使用父上下文中的变量来“保存”结果。这是example fiddle
    • 谢谢,我注意到.then((response1) => { const this.response1 = response1 })可以在第二个.then((response2) => { const response1 = this.response1 })中访问。
    猜你喜欢
    • 2018-06-22
    • 1970-01-01
    • 1970-01-01
    • 2022-01-21
    • 1970-01-01
    • 2022-11-18
    • 2019-09-29
    • 1970-01-01
    • 2016-05-12
    相关资源
    最近更新 更多