2014-01-05 147 views
0

我試圖向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(); 
+0

https:stackoverflow api的原因是https,但http工作正常。 –

+0

你可以嘗試添加'accept-encoding:'''來請求標題,如果它不起作用,你應該像這樣解碼gzip:http://stackoverflow.com/questions/8880741/node-js-easy-http-requests- with-gzip-deflate-compression – damphat

+0

此鏈接工作。 –

回答

0

#1的服務器配置錯誤,讓他們返回,即使你沒有問gzip壓縮體它。

看起來好像你必須在收到它之後對你的迴應進行gunzip。

+0

'curl'http://api.stackexchange.com/2.1/search/advanced?order=desc&sort=relevance&q=jsonp&site=stackoverflow'| gunzip -'對我來說工作得很好 – alex