我试图向here发出请求,如果你点击链接,你应该看到一个JSON响应(如预期的那样)。我已经尝试过https和http,这没什么关系(至少我不这么认为)。Nodejs http请求返回json格式不是json格式
无论如何,当我尝试从命令行得到响应时,我得到非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();
https:stackoverflow api的原因是https,但http工作正常。 –
你可以尝试添加'accept-encoding:'''来请求标题,如果它不起作用,你应该像这样解码gzip:http://stackoverflow.com/questions/8880741/node-js-easy-http-requests- with-gzip-deflate-compression – damphat
此链接工作。 –