Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
423 views
in Technique[技术] by (71.8m points)

node.js - Get a JSON via HTTP request in NodeJS

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...