【问题标题】:How to get body of response by HTTP POST request via library request如何通过库请求通过 HTTP POST 请求获取响应正文
【发布时间】:2020-01-30 04:42:52
【问题描述】:

我通过库请求发出 HTTP POST 请求,但无法获得响应的正文

在控制台日志中,我看到了正确的答案,但函数getBlock rerun 0

class BlockExplorer {
    private readonly request = require("request");
    private readonly options = {
        method: 'POST',
        url: 'https://example.com',
        headers:
        {
            Host: 'example.com'',
            Authorization: 'Basic basicBasicBasic=',
            'Content-Type': 'application/json'
        },
        json: true
    };

    async init() {
        const blockNum: Number = await this.getBlock();
        console.log(`Block num: ${blockNum}`);
    }

    private async getBlock() {
        let blockcount: Number = 0;
        var options = {
            body: { jsonrpc: '2.0', method: 'getblockcount', params: [] },
            ...this.options
        };

        await this.request(options, function (error, response, body) {
            if (error) throw new Error(error);
            console.log(body.result);
            blockcount = body.result;
        });

        return blockcount;
    }
}

new BlockExplorer().init();

我的控制台日志:

Block num: 0
617635

【问题讨论】:

  • await this.request() 不起作用,因为request() 不返回承诺。相反,使用request-promise 模块并摆脱回调。或者,由于 request() 处于维护模式并且不再获得新功能,请切换到已与 Promise 一起使用的 got() 模块。
  • 谢谢 - 它工作正常 - 只需使用 request-promise
  • @jfriend00 请发表您的评论作为答案
  • 根据您的要求,我写了一个答案。

标签: javascript node.js request


【解决方案1】:

await this.request() 不起作用,因为 request() 没有返回承诺,因此 await 没有任何用处。

改为使用request-promise 模块并摆脱回调。

或者,由于 request() 处于维护模式并且不再获得新功能,请切换到已与 Promise 一起使用的 got() 模块。

const rp = require('request-promise');

private async getBlock() {
    let blockcount: Number = 0;
    var options = {
        body: { jsonrpc: '2.0', method: 'getblockcount', params: [] },
        ...this.options
    };

    let body = await rp(options);
    console.log(body.result);
    blockcount = body.result;

    return blockcount;
}

2020 年 1 月编辑 - request() 模块处于维护模式

仅供参考,request 模块及其衍生模块(如 request-promise)现在处于维护模式,不会积极开发以添加新功能。您可以阅读更多关于推理的信息herethis table 中有一个备选方案列表,其中对每个备选方案进行了一些讨论。我自己一直在使用got(),它从一开始就是使用 Promise 构建的,而且使用简单。

【讨论】:

    【解决方案2】:

    问题在于您的request 电话。这是回调样式。这意味着将首先执行返回块计数,并在异步调用完成时执行blockcount = body.result;。这里有两种选择

    • 要么将回调样式转换为 Promise,然后在变量中获取结果。
    • 或在回调中返回响应。

    【讨论】:

      猜你喜欢
      • 2015-12-07
      • 2023-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多