You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

HTML表单提交数据至Google Sheet遭遇CORS访问错误求助

表单提交Google Sheet遇CORS错误解决方案

问题详情

尝试将HTML表单数据提交到Google Sheet时触发CORS错误,控制台报错:

Access to fetch at 'https://docs.google.com/spreadsheets/d/1ccRPWfXHazPS5Oe-mU-0x7bfIblyW-q_x6uQrOktpoo/edit#gid=0' from origin 'null' has been blocked by CORS policy: 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.

当前使用的HTML代码:

<html>
<body>
<form name="submit-to-google-sheet">
<input name="email" type="email" placeholder="Email" required>
<button type="submit">Send</button>
</form>
<script>
const scriptURL = 'https://docs.google.com/spreadsheets/d/1ccRPWfXHazPS5Oe-mU-0x7bfIblyW-q_x6uQrOktpoo/edit#gid=0'
const form = document.forms['submit-to-google-sheet']
form.addEventListener('submit', e => {
e.preventDefault()
fetch(scriptURL, { method: 'POST', body: new FormData(form)})
.then(response => console.log('Success!', response))
.catch(error => console.error('Error!', error.message))
})
</script>
</body>
</html>

当前状态:未编写code.gs代码,部署设置为允许所有Google账号用户访问。

解决方案

1. 编写Google Apps Script处理逻辑

打开目标Google Sheet,点击菜单栏「扩展程序」→「Apps Script」,在code.gs中写入以下代码:

function doPost(e) {
  const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  const data = e.parameter;
  // 追加表单数据到表格末尾,email对应表单input的name属性
  sheet.appendRow([data.email]);
  // 返回JSON格式成功响应
  return ContentService.createTextOutput(JSON.stringify({status: "success", data: data}))
    .setMimeType(ContentService.MimeType.JSON);
}

2. 重新部署Web App

  • 点击Apps Script界面右上角「部署」→「新部署」
  • 类型选择「Web应用」
  • 部署配置:
    • 执行:选择「我」(确保脚本拥有表格编辑权限)
    • 谁可以访问:选择「任何人,甚至匿名」(若需权限限制可调整,但匿名访问可规避CORS及登录验证问题)
  • 点击「部署」,复制生成的Web App地址(格式示例:https://script.google.com/macros/s/xxxxxx/exec)

3. 更新HTML中的提交地址

将HTML代码里的scriptURL替换为刚复制的Web App地址:

const scriptURL = 'https://script.google.com/macros/s/你的部署ID/exec'

4. 测试验证

保存修改后的HTML文件,重新测试表单提交,数据将通过Web App写入Google Sheet,CORS问题同时解决。

内容的提问来源于stack exchange,提问作者Mayuresh Deshmukh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 23:33:26