调用https://accounts.google.com/gsi/client遇CORS缺失Access-Control-Allow-Origin问题
问题概述
在学习Google Auth时,执行fetch("https://accounts.google.com/gsi/client")遇到CORS错误:
Access to script at 'https://accounts.google.com/gsi/client' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
预期与实际行为
- 预期:响应头包含
access-control-allow-origin: *,与调用https://apis.google.com/js/api.js时一致 - 实际:响应头无
Access-Control-Allow-Origin字段
复现步骤
在开发者工具控制台或脚本中执行fetch("https://accounts.google.com/gsi/client")即可复现。
解决方案
Google GSI客户端脚本不支持通过fetch加载,正确的使用方式是直接通过<script>标签嵌入到HTML中:
<script src="https://accounts.google.com/gsi/client" async defer></script>
原因说明
这类身份验证脚本的设计目标是通过浏览器直接加载执行,而非通过AJAX请求获取内容。因此服务器未配置CORS头允许fetch这类跨域AJAX请求,这是正常的设计逻辑,并非服务端错误。
内容的提问来源于stack exchange,提问作者Konstantin Solovev
相关产品推荐
相关产品推荐

