Chrome调用Google Cloud Function遭CORS拦截问题排查与解决
解决Chrome控制台向Google Cloud Function发送数据的CORS问题
问题描述
从Chrome开发者控制台向Google Cloud Function(GCF)发送POST请求时,持续被CORS策略拦截,报错信息如下:
Access to fetch at 'cloud function link' from origin 'https://chat.openai.com' 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. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
使用的前端JavaScript代码:
var data = { key: 'value' }; fetch('https://google cloud function link', { method: 'POST', mode: 'cors', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) }) .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error(error));
问题根源
CORS失败的核心原因是GCF代码执行中断:当GitHub仓库中已存在test_file_test_funct.txt文件时,代码末尾的repo.create_file(.....)会抛出错误,导致函数未完整执行,最终无法返回正确的CORS响应头。
修正后的GCF Python代码
import functions_framework @functions_framework.http def cors_enabled_function(request): # 处理预检请求(OPTIONS) if request.method == 'OPTIONS': # 设置CORS头,允许任意源的请求,缓存预检响应3600秒 headers = { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'GET', 'Access-Control-Allow-Headers': 'Content-Type', 'Access-Control-Max-Age': '3600' } return ('test', 204, headers) # 处理主请求,设置CORS头 headers = { 'Access-Control-Allow-Origin': '*' } from github import Github import os # 通过环境变量获取GitHub令牌 GIT_TOKEN = os.environ["GIT_TOKEN"] g = Github(GIT_TOKEN) # 查找目标仓库 target_repo = None for repo in g.get_user().get_repos(): if repo.name == "chat_gpt_results": target_repo = repo break if target_repo: # 捕获文件创建异常,避免函数中断 try: target_repo.create_file("test_file_test_funct.txt", "init commit", "file_content ------ ") except Exception as e: # 可在此添加日志记录,或根据需求处理文件已存在的情况 pass return (target_repo.name if target_repo else "未找到目标仓库", 200, headers)
补充说明
修正后的代码优化了两点:
- 完善了CORS预检请求和主请求的响应头设置,确保跨域请求能通过验证;
- 添加了仓库查找的容错逻辑,以及文件创建的异常捕获,避免因文件已存在等问题导致函数中断,保证CORS响应头能正常返回。
内容的提问来源于stack exchange,提问作者PdB
相关产品推荐
相关产品推荐

