我正在嘗試制作一個谷歌網路應用程式,但是當我發送一個獲取請求時,它給了我一個錯誤,說"_ 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"到 fetch 但什么也沒做 - 我嘗試添加
mode: "no-cors"到回傳空回應的 fetch
uj5u.com熱心網友回復:
修改點:
- 我認為在您的 Javascript 中,由于 GET 方法,不需要使用請求標頭。而且,我認為這可能是您的問題的原因。
- 而且,為了從您的 Web 應用程式中檢索作為 JSON 物件的值,如何修改
.then(response => {console.log(response);})為then(res => res.json()).then(res => console.log(res))? - 而且,當我看到您的 Google Apps 腳本時,我認為流程成本會變高,因為
getValue()它是在回圈中使用的。
當這些點反映在你的腳本中時,下面的修改怎么樣?
修改后的腳本:
Google Apps 腳本方面:
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 Apps 的 Google Apps Script 時,請將部署修改為新版本。這樣,修改后的腳本就會反映在 Web Apps 中。請注意這一點。
您可以在我的報告中查看詳細資訊“重新部署 Web 應用程式而不更改新 IDE 的 Web 應用程式的 URL(作者:我) ”中查看詳細資訊。
順便說一句,在這種情況下,從您的 Javascript 中,它假設您的 Web 應用程式部署為“執行身份:我”和“誰有權訪問該應用程式:任何人”。請注意這一點。
參考:
- 地圖()
- 基準測驗:使用 Google Apps 腳本讀寫電子表格(作者:我)
- 使用 Google Apps 腳本利用 Web Apps(作者:我)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/527092.html
上一篇:快速應用程式開發
