【发布时间】:2022-01-31 04:26:49
【问题描述】:
我正在尝试编写一个创建 HTTPS 请求的函数。
这都是使用 Typescript 的 expressjs 项目的一部分。
我可以让 HTTPS 请求正常工作并获得响应 - 但响应是使用 GZIP 编码的。我正在尽力遵循文档。但不走运,响应保持压缩状态。
这是我的代码
private getData = (host, pathname): Promise<string> => {
return new Promise((resolve, reject) => {
const options = {
hostname: host,
path: pathname,
gzip: true,
method: 'GET',
headers: {'x-apikey': 'XXXX'}
}
const req = https.request(options, (res) => {
if (res.statusCode < 200 || res.statusCode >= 300) {
console.log('error!')
return reject(new Error('statusCode=' + res.statusCode));
}
let body = '';
res.on('data', function (chunk) {
body += chunk;
});
res.on('end', function () {
try {
console.log('res.headers', res.headers)
console.log('res.headers', body)
body = JSON.parse.toString();
resolve(body);
} catch (e) {
reject(e);
}
resolve(body);
});
req.on('error', (e) => {
reject(e.message);
});
// send the request
});
req.end();
});
}
很明显,JSON 解析失败了。我错过了什么?
感谢大家的帮助
【问题讨论】: