2013-07-23 21 views
36

這裏是我的模型的JSON響應:獲得通過HTTP請求中的JSON的NodeJS

exports.getUser = function(req, res, callback) { 
    User.find(req.body, function (err, data) { 
     if (err) { 
      res.json(err.errors); 
     } else { 
      res.json(data); 
     } 
    }); 
}; 

在這裏,我通過http.request得到它。爲什麼我收到(數據)字符串而不是JSON?

var options = { 
    hostname: '127.0.0.1' 
    ,port: app.get('port') 
    ,path: '/users' 
    ,method: 'GET' 
    ,headers: { 'Content-Type': 'application/json' } 
}; 

var req = http.request(options, function(res) { 
    res.setEncoding('utf8'); 
    res.on('data', function (data) { 
     console.log(data); // I can't parse it because, it's a string. why? 
    }); 
}); 
reqA.on('error', function(e) { 
    console.log('problem with request: ' + e.message); 
}); 
reqA.end(); 

如何獲得json?

+0

JSON是一個序列化。只有JSON纔是字符串,否則還沒有被解析爲JavaScript。你在找'JSON.parse()'嗎? –

+0

這就是它。感謝Matt –

+0

我認爲'data'事件每次被調用多次,其參數是一個字符串數據的塊。在這種情況下返回的'data'是不是很可能會被破壞JSON,因爲它只是整個文檔的一小部分?我認爲你需要緩衝數據,然後在你的'end'事件中使用'JSON.parse()'。 – Sukima

回答

52

http發送/接收數據作爲字符串......這只是事情的方式。你正在尋找解析字符串爲json。

var jsonObject = JSON.parse(data); 

How to parse JSON using Node.js?

+2

...我的道歉,它比我想象的更簡單....謝謝你克里斯! –

+0

這真的很有用,thanx @ChrisCM –

45

只要告訴您正在使用JSON請求:真實,忘記頭和解析

var options = { 
    hostname: '127.0.0.1', 
    port: app.get('port'), 
    path: '/users', 
    method: 'GET', 
    json:true 
} 
request(options, function(error, response, body){ 
    if(error) console.log(error); 
    else console.log(body); 
}); 

與同爲後

var options = { 
    hostname: '127.0.0.1', 
    port: app.get('port'), 
    path: '/users', 
    method: 'POST', 
    json: {"name":"John", "lastname":"Doe"} 
} 
request(options, function(error, response, body){ 
    if(error) console.log(error); 
    else console.log(body); 
}); 
+0

我知道這個請求能夠給出一個JSON體,但是文檔真的不清楚那部分!節省冗餘分析。我也感覺你可以做'response.toJSON()' – CJxD

+2

這不適用於'http.request',而是[request](https://www.npmjs.com/package/request)。 – arve0

2

只設置json選項true,身體w ill包含解析的json:

request({ 
    url: 'http://...', 
    json: true 
}, function(error, response, body) { 
    console.log(body); 
});