gpt4 book ai didi

javascript - 获取 https 响应的正文

转载 作者:太空宇宙 更新时间:2023-11-04 00:45:35 25 4
gpt4 key购买 nike

我是 Nodejs 的新手,在尝试获取响应正文时遇到了一个奇怪的问题。好吧,为了打印出 body ,我们可能会做这样的事情,对吧? :

var https = require('https');
var request = https.get('https://teamtreehouse.com/arshankhanifar.json',function(response){
//print the data

response.setEncoding('utf8');
response.on('data', function (chunk){
console.log('BODY : ' + chunk); // Prints the body, no problem.
});
response.on('end', function() {
console.log('No more data in response.');
});
});

使用上面的代码,我可以打印出正文,它应该是一个包含 JSON 文件的字符串,但问题是,当我尝试将其保存在名为 body 的变量中时,当我打印它时,什么也没有出现! :

var https = require('https');
var request = https.get('https://teamtreehouse.com/arshankhanifar.json',function(response){
//save the data in a variable
var body = '';

response.setEncoding('utf8');
response.on('data', function (chunk){
body += chunk;
});

console.log(body); // prints nothing!
response.on('end', function() {
console.log('No more data in response.');

});
});

我希望我的问题足够清楚。如果有歧义,请要求澄清。

最佳答案

您正在触发 data 之前打印主体变量。

尝试如下所示。

var https = require('https');
var request = https.get('https://teamtreehouse.com/arshankhanifar.json',function(response){
//save the data in a variable
var body = '';

response.setEncoding('utf8');
response.on('data', function (chunk){
body += chunk;
});

response.on('end', function() {
console.log(body); // prints nothing!
console.log('No more data in response.');

});
});

引用:
https://nodejs.org/api/https.html#https_https_get_options_callback

关于javascript - 获取 https 响应的正文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34904603/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com