javascript - NodeJS : HTTP GET returns the code instead of JSON object

标签 javascript html json node.js http

我编写了以下 NodeJS 代码来从网站检索 json 对象

var http = require('http');
var url = {
  host: 'www.sample-website.com',
  headers: {
    "Accept": "application/json",
    'Content-Type': 'application/json'
  },
};
http.get(url, function(obj) {
  var output = "";
    for (property in obj) {
    output += property + obj[property] ;
}
console.log(output);

})

但是作为响应,我收到了一些我无法理解的代码(某种 events.js 代码)(不是 HTML 代码)。需要帮助找出我哪里出错了

包括供引用的代码片段::

 // emit removeListener for all listeners on all events
 if (arguments.length === 0) {
   for (key in this._events) {
     if (key === 'removeListener') continue;
     this.removeAllListeners(key);
   }
   this.removeAllListeners('removeListener');
   this._events = {};
   return this;
 }

最佳答案

根据 API 文档,http.get()通过 ServerResponse对其回调对象。您当前正在打印该对象(及其父对象)的属性。

如果你想获取响应正文,你应该在其数据事件上注册一个监听器:

res.on('data', function (chunk) {
  console.log('BODY: ' + chunk);
});

并重新组装 block 。

可以通过 res.statuscode 属性访问响应代码,res.headers 将为您提供数组中的响应 header 。

<小时/>

根据要求,这里是完整的示例代码:

var http = require('http');
var url = 'http://stackoverflow.com';
// ...
http.request(url, function (res) {
    console.log('STATUS: ' + res.statusCode);
    console.log('HEADERS: ' + JSON.stringify(res.headers));
    console.log('BODY: ');
    res.setEncoding('utf8');
    res.on('data', function (chunk) {
        process.stdout.write(chunk);
    });
}).end();

关于javascript - NodeJS : HTTP GET returns the code instead of JSON object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30556280/

相关文章:

linux - 如何让服务器每隔几秒获取一个 JSON 文件?

jquery - CSS:在一个位置垂直居中:绝对div

JavaScript 代码说明

javascript - 获取已经使用 Javascript/jQuery 加载的跨域 CSS 文件的全部内容?

javascript - 显示包含日期和其他记录的表

html - 在两列中成对对齐图像和段落而不重叠图像(wordpress)

java - 如何根据jquery中的特定父项在多个复选框中仅选中一个复选框

python - 提取 JSON 元素

javascript - Dynamo db Error adding question : { InvalidParameterType: Expected params. Item ['options' ].S 是一个字符串

javascript - 为什么 Vue 在替换或创建和删除数组项时使用不同的动画?