Blogspot iframe向Apps Script的doPost发POST请求遇CORS问题
解决Google Apps Script跨域POST请求的CORS错误
问题根源
你的iframe页面托管在script.googleusercontent.com域名下,向GAS部署链接发送POST请求时,浏览器会触发预请求(OPTIONS),但GAS默认未处理OPTIONS请求,且POST响应缺少CORS允许头,导致被浏览器拦截。
解决方案
需要在GAS中添加OPTIONS请求处理函数,并在POST响应中注入CORS头,同时确保fetch请求配置正确。
1. 修改GAS的.gs文件,添加跨域处理逻辑
function doGet() { const html = HtmlService.createHtmlOutputFromFile("blogspot"); return html.setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL); } // 处理浏览器OPTIONS预请求 function doOptions(e) { const corsHeaders = { "Access-Control-Allow-Origin": "*", // 生产环境建议替换为你的Blogspot域名或iframe的origin "Access-Control-Allow-Methods": "POST, OPTIONS", "Access-Control-Allow-Headers": "Content-Type" }; return ContentService.createTextOutput("") .setMimeType(ContentService.MimeType.TEXT) .setHeaders(corsHeaders); } // 处理POST请求并返回带CORS头的响应 function doPost(e) { // 这里编写你的POST业务逻辑,比如解析请求参数 const requestData = JSON.parse(e.postData.contents); const responseData = { status: "success", received: requestData }; // 注入CORS允许头 const corsHeaders = { "Access-Control-Allow-Origin": "*", // 建议指定具体域名提升安全性 "Content-Type": "application/json" }; return ContentService.createTextOutput(JSON.stringify(responseData)) .setMimeType(ContentService.MimeType.JSON) .setHeaders(corsHeaders); }
2. 调整iframe内的fetch请求配置
确保请求头和参数格式正确,示例:
fetch('https://script.google.com/macros/s/.../exec', { method: 'POST', headers: { 'Content-Type': 'application/json', // 必须与GAS允许的头一致 }, body: JSON.stringify({ username: "test", data: "example" }) // 你的请求数据 }) .then(res => res.json()) .then(result => console.log("处理结果:", result)) .catch(err => console.error("请求失败:", err));
3. 重新部署GAS
- 部署类型选择Web应用
- 执行权限设置为任何人,甚至匿名(如果不需要用户登录)
- 点击“部署”,替换iframe中的GAS链接为最新部署地址
关键注意事项
Access-Control-Allow-Origin尽量指定具体域名(比如你的Blogspot域名或iframe的script.googleusercontent.com子域名),避免使用*,提升安全性。- 如果你的GAS需要用户认证,需额外处理OAuth2逻辑,此时不能使用匿名部署,CORS配置也需调整为允许认证域名。
内容的提问来源于stack exchange,提问作者John Simon
相关产品推荐
相关产品推荐

