2015-05-31 91 views
0

我寫了下面的代碼的NodeJS從網站的NodeJS:HTTP GET返回代碼,而不是

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); 

}) 

但是作爲迴應,我得到了一些代碼(某種事件的檢索JSON對象JSON對象.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; 
} 
+0

只是一個友善的建議,請使用要快的框架或連接 – binariedMe

回答

2

根據 API文檔,http.get()傳遞一個ServerResponse對象的回調。您目前正在打印該對象(及其父母的)屬性。

如果你想要得到的響應主體,應在其數據事件註冊一個監聽器:

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

和重新組裝塊。

響應代碼可以通過res.statuscode屬性訪問,而res.headers會給你一個數組中的響應頭。


按照要求,這裏是一個完整的示例代碼:

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(); 
相關問題