浏览器的Google Contacts API被CORS政策阻止

时间:2018-11-20 18:37:12

标签: google-api cors google-contacts gsuite googlecontactsapi

在开发环境中,我的浏览器无法向Google Contacts API发出请求。

我正在尝试通过向https://localhost:3001发出XHR请求来从托管在https://www.google.com/m8/feeds/contacts/default/thin?alt=json&access_token=MYTOKEN&max-results=5000&v=3.0的Web应用请求联系人供稿

我们以前一直使用JSONP发出此请求(如在其他帮助论坛中所建议的那样),但是最近由于以下错误而开始失败:

Refused to execute script from 'https://www.google.com/m8/feeds/contacts/default/thin?alt=json&access_token=MYTOKEN&max-results=5000&v=3.0&callback=jQuery33107099178438653957_1542737952472&_=1542737952473' because its MIME type ('application/json') is not executable, and strict MIME type checking is enabled.

我知道这现在失败了,因为浏览器正在检查响应的模仿类型,并且因为它不是application/javascript,因此不应将其视为脚本进行评估,因此JSONP无法正常工作。我们尝试要求提供application/javascript,但似乎API不会为我们提供该模仿类型的响应。

现在,我们正在尝试清理行为,但我们遇到了一个CORS问题,我想这是整个Internet一直在相互告诉对方首先使用JSONP的原因。

当我们尝试在不使用JSONP的情况下发出请求时,会出现此错误

Access to XMLHttpRequest at 'https://www.google.com/m8/feeds/contacts/default/thin?alt=json&access_token=MYTOKEN&max-results=5000&v=3.0' from origin 'https://localhost:3001' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

但是,在Google support forum的深处,有人建议使用googleapis.com而不是google.com。作为百灵鸟,我们尝试了它,并且确实起作用了。我现在的问题是我不知道为什么会这样或它将继续工作。 docs并未提及使用此新主机,而是提及了googleapis.com URL作为只读OAuth范围,但这似乎与此问题有关。 googleapis.com确实是我们用于从浏览器获取联系人的新主机名吗?

编辑:包括发出请求的代码

const params = $.param({
  alt: 'json',
  access_token: 'MYTOKEN',
  'max-results': 5000,
  v: '3.0'
})
const url = `https://www.google.com/m8/feeds/contacts/default/thin?${params}` # when I change this to www.googleapis.com it works
$.get(url, responseHandler)

编辑:由于某种原因,我的浏览器正在发送的CORS预检OPTIONS请求中包括请求标头:

Accept: text/html,application/xhtml+xm…plication/xml;q=0.9,*/*;q=0.8
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.5
Access-Control-Request-Headers: x-csrf-token
Access-Control-Request-Method: GET
Cache-Control: no-cache
Connection: keep-alive
Host: www.google.com
Origin: https://localhost:3001
Pragma: no-cache
User-Agent: Mozilla/5.0 (Macintosh; Intel …) Gecko/20100101 Firefox/63.0

1 个答案:

答案 0 :(得分:0)

由于@sideshowbarker的评论,我们发现我们有一个jQuery ajaxPrefilter配置为向任何跨域ajax请求添加x-csrf-token标头。这导致浏览器发送失败的CORS预检OPTIONS请求。

在我们的例子中,x-csrf-token标头的来源是一个称为ember-cli-rails-addon的依赖项,该依赖项将x-csrf-token添加到所有请求中。该项目here的PR可以解决该问题。