我正在執行對返回簡單JSON對象的url的get請求。Node.js中的JSON.parse問題
這裏是網址:http://live.albiononline.com/status.txt
正如你可以看到它是一個文本文件,它的內容類型標題爲text/plain。當我收到的身體日誌,它是:
{ "status": "online", "message": "All good." }
但是當我嘗試登錄,它body.status是不確定的。當我做var data = JSON.parse(body);
然後console.log(data.status);
我得到:
undefined:1
{ "status": "online", "message": "All good." }
^
SyntaxError: Unexpected token in JSON at position 0
任何想法發生了什麼?我認爲它與從.txt文件中提取的事實有關?
UPDATE:
request('http://live.albiononline.com/status.txt', function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body); // { "status": "online", "message": "All good." }
console.log(body.status); // undefined
}
});
它已經JSON對象。你不需要解析 – RaR
在我的問題中,我說'但是當我嘗試登錄時,body.status它是未定義的。' – TJH
你可以告訴我你的代碼一次 –