【发布时间】: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