谷歌表单web应用程序在前端发送获取请求时被CORS阻止



我正试图制作一个谷歌网络应用程序,但当我发送获取请求时,它会给我一个错误,说"_ has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource."
Javascript(仅前端(:

fetch("https://script.google.com/macros/s/.../exec", {
method: "GET",
headers: {
"Content-Type": "application/json"
}
}).then(response => {
console.log(response);
});

应用程序脚本:

function doGet(e) {
// get spreadsheet
const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheetByName('DataCollection');
const max = sheet.getRange("F1").getValue();
// get data and sort by amount
const data = [];
for (let i = 1; i <= max; i++) {data.push({name: sheet.getRange("B" + i).getValue(), data: sheet.getRange("A" + i).getValue()});}
data.sort((a, b) => (a.data > b.data) && -1 || 1);
return ContentService.createTextOutput(JSON.stringify(data)).setMimeType(ContentService.MimeType.JSON);
}

目前,web应用程序的部署设置为以我自己的身份执行,任何人都可以访问,并且我的网页是静态的。

当我测试代码时,网络应用程序运行得很好,但当我通过网页发送请求时,CORS会阻止它。我尝试了多种对其他人有效的解决方案,但我一直得到相同的结果。

我尝试过的解决方案:

jQuery.ajax({
crossDomain: true,
url: "https://script.google.com/macros/s/.../exec",
method: "GET",
dataType: "jsonp",
success: response => console.log(response)
});
  • 我尝试将redirect: "follow"添加到提取中,但没有成功
  • 我尝试将mode: "no-cors"添加到获取中,结果返回空响应

修改点:

  • 我认为在您的Javascript中,由于GET方法,不需要使用请求头。而且,我认为这可能是你的问题的原因
  • 而且,为了将Web应用程序中的值作为JSON对象检索,将.then(response => {console.log(response);})修改为then(res => res.json()).then(res => console.log(res))如何
  • 而且,当我看到你的谷歌应用程序脚本时,我认为流程成本会变得很高,因为getValue()是在循环中使用的

当这些点反映在脚本中时,下面的修改如何?

修改的脚本:

谷歌应用程序脚本端:

function doGet(e) {
const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheetByName('DataCollection');
const max = sheet.getRange("F1").getValue();
const data = sheet.getRange("A1:B" + sheet.getLastRow()).getValues().splice(0, max).map(([data, name]) => ({ name, data }));
data.sort((a, b) => (a.data > b.data) && -1 || 1);
return ContentService.createTextOutput(JSON.stringify(data)).setMimeType(ContentService.MimeType.JSON);
}
  • 在您的脚本中,似乎没有使用事件对象e

Javascript端:

fetch("https://script.google.com/macros/s/###/exec") // Please set your Web Apps URL.
.then(res => res.json())
.then(res => console.log(res));

注:

  • 当我测试您的显示脚本时,我确认了与CORS相关的相同问题。而且,当我提出的脚本被使用时,我确认该问题已被删除。

  • 当您修改Web应用程序的Google Apps脚本时,请将部署修改为新版本。这样,修改后的脚本就会反映在Web应用程序中。请小心

  • 你可以在我的报告中看到这方面的细节;在不改变用于新IDE的Web应用程序的URL的情况下重新部署Web应用程序(作者:我(";。

  • 顺便说一句,在这种情况下,根据您的Javascript,它假设您的Web应用程序部署为";执行为:Me";以及";谁可以访问该应用程序:任何人;。请小心

参考文献:

  • map((
  • 基准:使用谷歌应用程序脚本阅读和编写电子表格(作者:我(
  • 利用谷歌应用程序脚本的Web应用程序(作者:我(

最新更新