使用 Node.js 调用 JSON API

IT技术 javascript json node.js http
2021-02-07 00:38:23

我正在尝试获取登录到我的应用程序的用户的 Facebook 个人资料图片。Facebook 的 API 声明http://graph.facebook.com/517267866/?fields=picture将正确的 URL 作为 JSON 对象返回。

我想从我的代码中获取图片的 URL。我尝试了以下操作,但我在这里遗漏了一些东西。

 var url = 'http://graph.facebook.com/517267866/?fields=picture';

 http.get(url, function(res) {
      var fbResponse = JSON.parse(res)
      console.log("Got response: " + fbResponse.picture);
    }).on('error', function(e) {
      console.log("Got error: " + e.message);
 });

运行此代码会产生以下结果:

undefined:1

^
SyntaxError: Unexpected token o
    at Object.parse (native)
6个回答

回调中res参数http.get()不是正文,而是一个http.ClientResponse对象。你需要组装身体:

var url = 'http://graph.facebook.com/517267866/?fields=picture';

http.get(url, function(res){
    var body = '';

    res.on('data', function(chunk){
        body += chunk;
    });

    res.on('end', function(){
        var fbResponse = JSON.parse(body);
        console.log("Got a response: ", fbResponse.picture);
    });
}).on('error', function(e){
      console.log("Got an error: ", e);
});
哇,这比我对这个时代的标准库的期望要低。
2021-03-20 00:38:23
JSON.parse()对无效的 JSON 抛出异常,并且应该始终在try/catch内调用,否则整个程序可能会因无效数据而崩溃(有时会发生)。
2021-03-23 00:38:23
request module会为你处理简单的 http get/post/etc.. github.com/request/request
2021-03-24 00:38:23
为避免必须执行try/catchfor JSON.parse如果您使用,则应始终执行JSON.parse- 请参阅此答案),您可以使用这样的modulerequest该module可以为您自动解析 JSON,正如我在下面的答案中所示。
2021-03-30 00:38:23
res 参数现在实际上是一个http.IncomingMessage对象。据我所知,ClientResponse 类已从节点的 http 库中重构出来。
2021-04-08 00:38:23

其他答案的问题:

  • 不安全 JSON.parse
  • 没有响应代码检查

这里的所有答案都JSON.parse()不安全的方式使用您应该始终将所有调用JSON.parse()放在一个try/catch块中,尤其是当您解析来自外部源的 JSON 时,就像您在这里所做的那样。

您可以使用request自动解析其他答案中未提及的 JSON。已经有一个使用requestmodule的答案,但它用于JSON.parse()手动解析 JSON - 应该始终try {} catch {}内运行以处理不正确的 JSON 错误,否则整个应用程序将崩溃。并且会发生不正确的 JSON,相信我。

使用的其他答案http也使用JSON.parse()而不检查可能发生的异常并使您的应用程序崩溃。

下面我将展示几种安全处理它的方法。

所有示例都使用公共 GitHub API,因此每个人都可以安全地尝试该代码。

示例与 request

这是一个request自动解析 JSON的工作示例

'use strict';
var request = require('request');

var url = 'https://api.github.com/users/rsp';

request.get({
    url: url,
    json: true,
    headers: {'User-Agent': 'request'}
  }, (err, res, data) => {
    if (err) {
      console.log('Error:', err);
    } else if (res.statusCode !== 200) {
      console.log('Status:', res.statusCode);
    } else {
      // data is already parsed as JSON:
      console.log(data.html_url);
    }
});

用实施例httptry/catch

这使用https-如果您想要 HTTP 连接,只需更改httpshttp

'use strict';
var https = require('https');

var options = {
    host: 'api.github.com',
    path: '/users/rsp',
    headers: {'User-Agent': 'request'}
};

https.get(options, function (res) {
    var json = '';
    res.on('data', function (chunk) {
        json += chunk;
    });
    res.on('end', function () {
        if (res.statusCode === 200) {
            try {
                var data = JSON.parse(json);
                // data is available here:
                console.log(data.html_url);
            } catch (e) {
                console.log('Error parsing JSON!');
            }
        } else {
            console.log('Status:', res.statusCode);
        }
    });
}).on('error', function (err) {
      console.log('Error:', err);
});

用实施例httptryjson

这个例子与上面的类似,但使用了tryjsonmodule。(免责声明:我是该module的作者。)

'use strict';
var https = require('https');
var tryjson = require('tryjson');

var options = {
    host: 'api.github.com',
    path: '/users/rsp',
    headers: {'User-Agent': 'request'}
};

https.get(options, function (res) {
    var json = '';

    res.on('data', function (chunk) {
        json += chunk;
    });

    res.on('end', function () {
        if (res.statusCode === 200) {
            var data = tryjson.parse(json);
            console.log(data ? data.html_url : 'Error parsing JSON!');
        } else {
            console.log('Status:', res.statusCode);
        }
    });
}).on('error', function (err) {
      console.log('Error:', err);
});

概括

使用的例子request是最简单的。但是,如果由于某种原因您不想使用它,那么请记住始终检查响应代码并安全地解析 JSON。

我认为对于像这样的简单 HTTP 请求,最好使用requestmodule您需要使用 npm ( npm install request)安装它,然后您的代码可能如下所示:

const request = require('request')
     ,url = 'http://graph.facebook.com/517267866/?fields=picture'

request(url, (error, response, body)=> {
  if (!error && response.statusCode === 200) {
    const fbResponse = JSON.parse(body)
    console.log("Got a response: ", fbResponse.picture)
  } else {
    console.log("Got an error: ", error, ", status code: ", response.statusCode)
  }
})
2021年仍然有效
2021-03-20 00:38:23

我使用的get-json使用起来非常简单:

$ npm install get-json --save

进口 get-json

var getJSON = require('get-json')

要执行GET请求,您可以执行以下操作:

getJSON('http://api.listenparadise.org', function(error, response){
    console.log(response);
})

另一种解决方案是用户axios

npm install axios

代码将类似于:

const url = `${this.env.someMicroservice.address}/v1/my-end-point`;

const { data } = await axios.get<MyInterface>(url, {
  auth: {
    username: this.env.auth.user,
    password: this.env.auth.pass
  }
});

return data;