首页 > 解决方案 > 如何通过库请求通过 HTTP POST 请求获取响应正文

问题描述

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

在控制台日志中,我看到了正确的答案,但函数getBlockrerun 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

标签: javascriptnode.jsrequest

解决方案


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

相反,使用request-promise模块并摆脱回调。

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

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现在处于维护模式,不会积极开发以添加新功能。您可以在此处阅读有关推理的更多信息。此表中有一个备选方案列表,并对每个备选方案进行了一些讨论。我一直在使用got()自己,它从一开始就是使用 Promise 构建的,并且易于使用。


推荐阅读