Get a JSON via HTTP request in NodeJS
Jsonnode.jsApiHttprequestJson Problem Overview
Here is my model with a JSON response:
exports.getUser = function(req, res, callback) {
User.find(req.body, function (err, data) {
if (err) {
res.json(err.errors);
} else {
res.json(data);
}
});
};
Here I get it via http.request
. Why do I receive (data) a string and not a 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();
How can I get a JSON?
Json Solutions
Solution 1 - Json
http sends/receives data as strings... this is just the way things are. You are looking to parse the string as json.
var jsonObject = JSON.parse(data);
https://stackoverflow.com/questions/5726729/how-to-parse-json-using-nodejs
Solution 2 - Json
Just tell request that you are using json:true and forget about header and 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);
});
and the same for post
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);
});
Solution 3 - Json
Just setting json
option to true
, the body will contain the parsed JSON:
request({
url: 'http://...',
json: true
}, function(error, response, body) {
console.log(body);
});