Hier is mijn model met een JSON-antwoord:
exports.getUser = function(req, res, callback) {
User.find(req.body, function (err, data) {
if (err) {
res.json(err.errors);
} else {
res.json(data);
}
});
};
Hier krijg ik het via http.request
. Waarom ontvang ik (data) een string en geen 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();
Hoe kan ik een JSON krijgen?
Antwoord 1, autoriteit 100%
http verzendt/ontvangt data als strings… zo gaat het nu eenmaal. U wilt de string ontleden als json.
var jsonObject = JSON.parse(data);
Hoe JSON te parseren met Node.js?
Antwoord 2, autoriteit 86%
Vertel het verzoek gewoon dat je json:true gebruikt en vergeet header en parse
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);
});
en hetzelfde voor bericht
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);
});
Antwoord 3, autoriteit 25%
Als je de optie json
instelt op true
, zal de hoofdtekst de geparseerde JSON bevatten:
request({
url: 'http://...',
json: true
}, function(error, response, body) {
console.log(body);
});