70

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?

Syscall
  • 19,327
  • 10
  • 37
  • 52
Sasha Grey
  • 976
  • 1
  • 9
  • 17
  • JSON is a serialization. It's only JSON if it's in a string, or otherwise not-yet-parsed as JavaScript. Are you looking for `JSON.parse()`? – Matt Ball Jul 23 '13 at 13:42
  • I thought the `data` event was called multiple times each time with an argument that is a chunk of the string data. Wouldn't it be quite likely that the `data` returned in that event be broken JSON because it's only a fraction of the total document? I think you need to buffer the data and then use `JSON.parse()` in your `end` event. – Sukima Sep 17 '14 at 02:01
  • You're right, it sends in chunks , so the best way is create a Buffer array and push it there – jeveloper Jul 30 '15 at 00:58
  • Seeing nodejs question asked by Sasha Grey....:D – Sebastian Dec 28 '21 at 19:00
  • Also notice that reqA is not defined in your code – Holdsworth Jan 19 '22 at 13:08

3 Answers3

88

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);

How to parse JSON using Node.js?

Community
  • 1
  • 1
MobA11y
  • 18,425
  • 3
  • 49
  • 76
75

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);
});
dpineda
  • 2,401
  • 27
  • 25
  • 1
    I knew that request was able to give a JSON body but the documentation really wasn't clear on that part! Saves doing a redundant parse. I also get the feeling you can do `response.toJSON()` – Chris Watts Nov 25 '15 at 03:18
  • 12
    This does not work for `http.request`, rather [request](https://www.npmjs.com/package/request). – arve0 Oct 10 '17 at 18:32
25

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);
});
Syscall
  • 19,327
  • 10
  • 37
  • 52
José Antonio Postigo
  • 2,674
  • 24
  • 17