Qui è il mio modello con una risposta JSON:Prendi un JSON via HTTP Request in NodeJS
exports.getUser = function(req, res, callback) {
User.find(req.body, function (err, data) {
if (err) {
res.json(err.errors);
} else {
res.json(data);
}
});
};
Qui ho capito tramite http.request. Perché ricevo (dati) una stringa e non un 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();
Come posso ottenere un JSON?
JSON è una serializzazione. È solo JSON se si trova in una stringa, o altrimenti non ancora analizzato come JavaScript. Stai cercando 'JSON.parse()'? –
questo è tutto. grazie Matt –
Ho pensato che l'evento 'data' è stato chiamato più volte ogni volta con un argomento che è un blocco dei dati di stringa. Non sarebbe molto probabile che il 'data' restituito in quell'evento sia rotto JSON perché è solo una frazione del documento totale? Penso che sia necessario bufferizzare i dati e quindi usare 'JSON.parse()' nell'evento 'end'. – Sukima