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

如何在React中使用Google Apps Script解决私有表格对接的CORS问题

React项目对接私有Google Sheets的CORS问题咨询

我需要让面向员工的React表单站点与私有Google Sheets进行数据收发,老板需要通过表格查看表单回复。尝试了三种方案均未成功:

  • 使用Node.js调用Sheets API:项目无法部署Node.js,且不熟悉该用法
  • 在React中直接用JS调用Sheets API:需引入大量陌生库,未能配置成功
  • 使用Google Apps Script编写读取表格并返回JSON的函数,但React调用时遭遇CORS策略限制

错误信息

localhost/:1
Access to XMLHttpRequest at 'https://script.google.com/macros/s/AKfycbxuz7xwcOu77AqEsAnnOS0MeQ2qu5D47ZnGRhMS3su_OegiNeyyFdoY3cK3svybyBZb/exec' from origin 'http://localhost:3000' 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.

我的React代码

const obj = {
    redirect: "follow",
    method: "POST",
    headers: {
        'Access-Control-Allow-Origin': '*',
        "Content-Type": "text/plain;charset=utf-8",
    },
};
const url = "https://script.google.com/macros/s/AKfycbxuz7xwcOu77AqEsAnnOS0MeQ2qu5D47ZnGRhMS3su_OegiNeyyFdoY3cK3svybyBZb/exec";
axios.get(url, obj)
    .then((response) => {
        console.log(response);});

我的Apps Script代码

function doGet(e) {
  const ss = SpreadsheetApp.openById("1Qo78FwRfUBE20q3uJO4me-I30yd9IO64_cf48OER2Qk").getSheetByName("pag1");
  const values = ss.getDataRange().getValues();


  //Headers
  const headers = values[0];
  //Values
  const info = values.slice(1);


  const holder = [];
  info.forEach((ele, ind)=>{
    const temp = {};

    headers.forEach((header,index) =>{
      header = header.toLowerCase();
      temp[header] = ele[index];
    });

    holder.push(temp);
  });

    Logger.log(holder);

  const output = JSON.stringify({
    status: true,
    data: holder
  });

  return ContentService.createTextOutput(output).setMimeType(ContentService.MimeType.JSON);
}

设置mode:"no-cors"则无法获取数据,请问我哪里操作有误?


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 02:30:51