关于node.js:通过NodeJS中的Http Request获取json

Get a json via Http Request in NodeJS

这是我的模型与json响应:

1
2
3
4
5
6
7
8
9
exports.getUser = function(req, res, callback) {
    User.find(req.body, function (err, data) {
        if (err) {
            res.json(err.errors);
        } else {
            res.json(data);
        }
   });
};

在这里,我通过http.request获得它。 为什么我收到(数据)字符串而不是json?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
 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();

我怎么能得到一个json?


http以字符串形式发送/接收数据......这就是事情的方式。 您正在寻找将字符串解析为json。

1
var jsonObject = JSON.parse(data);

如何使用Node.js解析JSON?


只是告诉请求您正在使用json:true并忘记标题和解析

1
2
3
4
5
6
7
8
9
10
11
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);
});

和帖子相同

1
2
3
4
5
6
7
8
9
10
11
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);
});


只需将json选项设置为true,正文将包含已解析的json:

1
2
3
4
5
6
request({
  url: 'http://...',
  json: true
}, function(error, response, body) {
  console.log(body);
});