在 NodeJS 中通过 Http 请求获取 json

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17811827/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 15:06:28  来源:igfitidea点击:

Get a json via Http Request in NodeJS

jsonnode.jsapihttprequest

提问by Sasha Grey

Here is my model with a json response:

这是我的带有 json 响应的模型:

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?

在这里,我通过 http.request 获取它。为什么我收到(数据)一个字符串而不是一个 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?

回答by ChrisCM

http sends/receives data as strings... this is just the way things are. You are looking to parse the string as json.

http 以字符串的形式发送/接收数据......事情就是这样。您希望将字符串解析为 json。

var jsonObject = JSON.parse(data);

How to parse JSON using Node.js?

如何使用 Node.js 解析 JSON?

回答by dpineda

Just tell request that you are using json:true and forget about header and parse

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

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

回答by José Antonio Postigo

Just setting jsonoption to true, the body will contain the parsed json:

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

request({
  url: 'http://...',
  json: true
}, function(error, response, body) {
  console.log(body);
});