Nodejs http请求以json格式返回json

时间:2014-01-05 07:05:38

标签: javascript json node.js

我正在尝试向here发出请求,如果您点击该链接,您应该会看到JSON响应(如预期的那样)。我试过https和http,它没关系(至少我不这么认为)。

无论如何,当我尝试从命令行获得响应时,我得到非UTF-8字符,如 B E 9作为响应,即使我指定utf-8编码。我已经尝试了npm模块请求并执行节点http / https请求。

我只需要返回一个JSON响应。

我也尝试过JSON.parse(),但无济于事。

这是我试过的代码

var request = require("request")

var url = endpoint;

request({
    url: url,
    json: true
}, function (error, response, body) {

if (!error && response.statusCode === 200) {
    console.log(body); // Print the json response
}
})

和基本的http请求

var endpoint = 'http://api.stackexchange.com/2.1/search/advanced?order=desc&sort=relevance&q=jsonp&site=stackoverflow';
var req = http.request(endpoint, function(res) {
  res.setEncoding('utf8');
  res.on('data', function (chunk) {
    console.log('BODY: ' + chunk);
  });
});

req.on('error', function(e) {
  console.log('problem with request: ' + e.message);
});

// write data to request body
req.write('data\n');
req.write('data\n');
req.end();

1 个答案:

答案 0 :(得分:0)

Stackoverflow服务器配置错误,因此即使您没有要求,它们也会返回gzip编码的正文。

看起来你必须在收到回复之后对其进行枪杀。

相关问题