2017-04-04 51 views
1

我一直在使用Google+ API玩耍,并试图让这个网址是Google+用户的个人资料图片网址:

https://www.googleapis.com/plus/v1/people/ {} USER_ID键= { API_KEY}

无需OAuth的,你也可以尝试一下这里(无需API密钥):

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

起初我使用的提取API来获取数据,因为我也想用一个服务人员要做到这一点:

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的情况下解决问题,以便我仍然可以在服务人员中执行此异步任务?

+0

很可能google会以json格式向您发送回复。 –

回答

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

看起来像你的解决方案的作品!我只是编辑了一下,使输出一致。但是,我们怎么知道我们得到的是一个json? @GregL – kevguy

+0

你应该知道你期望从你打电话给的API。使用'.getJSON()',你总是假设JSON,所以两种方法之间返回类型的假设没有什么区别。 – GregL

+0

谢谢,很好的答案! – kevguy