javascript - 如何通过库请求通过 HTTP POST 请求获取响应正文
问题描述
我通过库请求发出 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
解决方案
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 构建的,并且易于使用。
推荐阅读
- swift - 用于条件绑定的 Swift Initializer 必须具有 Optional 类型,而不是 if let 语句的“Bool”错误
- mongodb - 使用 mongo-db updateMany 查询的语法错误
- sql - 在 scala 中选择几个大的 sql 后,JDBC 变得非常慢
- javascript - 为什么我面临语音 RSS api 的一些问题
- javascript - 为什么不再为我的注册表单生成 stripeTokens?
- swift - 从查询中检索 Firestore 文档计数以在 UIcollectionView 单元格计数中使用,Swift 4.0
- django - 代码应该打印特定用户的帖子,但它正在打印所有用户的帖子
- mysql - 是否可以创建这样的 MySQL 查询?
- java - Java JPA - 如何使用列表放置对象并使用 CRUD 更新列表对象?
- angular - 导入模块以在其他模块中部分使用