如何通过库请求通过HTTP POST请求获取响应正文

问题描述 投票:0回答:1

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

在控制台日志中,我看到了正确的答案,但函数getBlock重新运行了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
javascript node.js request
1个回答
0
投票
问题是您的request电话。这是回调样式。这意味着将在异步调用完成后首先执行返回块计数,并执行blockcount = body.result;。您有两种选择]

    将回调样式转换为promise并将结果保存在变量中。
  • 或在您的回调中返回响应。
© www.soinside.com 2019 - 2024. All rights reserved.