fetch 和 $.getjson 的区别
Difference between fetch and $.getjson
我一直在研究 Google+ API 并尝试使用此 url 获取 Google+ 用户的个人资料图片 url =]:
https://www.googleapis.com/plus/v1/people/{user_id}?key={API_KEY}
不需要 OAuth,您也可以在这里尝试一下(不需要 API 密钥):
起初我使用 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 中执行此异步任务?
更改 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);
});
我一直在研究 Google+ API 并尝试使用此 url 获取 Google+ 用户的个人资料图片 url =]:
https://www.googleapis.com/plus/v1/people/{user_id}?key={API_KEY}
不需要 OAuth,您也可以在这里尝试一下(不需要 API 密钥):
起初我使用 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 中执行此异步任务?
更改 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);
});