【问题标题】:Difference between fetch and $.getjsonfetch 和 $.getjson 之间的区别
【发布时间】:2017-08-29 07:45:51
【问题描述】:

我一直在使用 Google+ API 并尝试使用此网址获取 Google+ 用户的个人资料图片网址:

https://www.googleapis.com/plus/v1/people/{user_id}?key={API_KEY}

不需要 OAuth,您也可以在这里尝试一下(不需要 API 密钥):

https://developers.google.com/apis-explorer/#p/plus/v1/plus.people.get?userId=116725099929439898086&_h=1&

起初我使用 Fetch API 来获取数据,因为我也想使用 service worker 来做到这一点:

fetch('https://www.googleapis.com/plus/v1/people/116725099929439898086?key=MY_API_KEY')
.then(function(response){
    console.log(response);
});

但它只给我这个回应:

{
    body: ReadableStream
    bodyUsed: false
    headers: Headers
    ok: true
    status: 200
    statusText: ""
    type: "cors"
    url: "https://www.googleapis.com/plus/v1/people/115681458968227650592?key=MY_API_KEY"
}

但是,如果我改用 jQuery 的 getJSON 方法:

$.getJSON( "https://www.googleapis.com/plus/v1/people/115681458968227650592?key=MY_API_KEY", function( data ) {
    console.log(data);
}); 

它就像一个魅力,我可以得到我需要的东西:

{
 "kind": "plus#person",
 "etag": "\"FT7X6cYw9BSnPtIywEFNNGVVdio/DgskSQn7XXHCvjcdFBFkiqEbsfo\"",
 "gender": "male",
 "urls": [ ... ],
 "objectType": "person",
 "id": "116725099929439898086",
 "displayName": "Kevin Lai",
 ...
}

有人能解释为什么他们会接受如此不同的行为吗?另外,如何在仍然使用 Fetch API 的同时解决问题,以便我仍然可以在 service worker 中执行此异步任务?

【问题讨论】:

  • 可能是 google 以 json 格式向您发送响应。

标签: javascript jquery fetch-api


【解决方案1】:

fetch() 调用更改为使用response.json()(请参阅MDN docs)从响应正文中提取JSON。

fetch('https://www.googleapis.com/plus/v1/people/116725099929439898086?key=MY_API_KEY')
.then(function (response){
    return response.json();
})
.then(function (json){
    console.log(json);
});

【讨论】:

  • 看起来您的解决方案有效!我只是对其进行了一些编辑以使输出保持一致。但是我们如何判断我们得到的是不是 json 呢? @GregL
  • 您应该知道您对所调用 API 的期望。使用$.getJSON(),无论如何您都在假设 JSON,因此两种方法之间的返回类型假设没有区别。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-15
  • 2014-11-17
  • 2018-03-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多