Search code examples
google-sheetsgoogle-apps-scriptcors

CORS error when using App script to write data to google sheet


I'm using the App script to post data from my web app and write into Sheet but failed with CORS error tried few code suggested by others

Here is the code on App script:

function doPost(e) {
var params = e.postData;
var selected = params.selectedYear;
var ss = SpreadsheetApp.openById("1GeHldpOtB9CZAQjVZH66HJvPAAj7"); 
var sheet = ss.getSheetByName("Sheet1");
var lastRow = sheet.getLastRow();

 sheet.getRange(lastRow + 1, 1).setValue(selected);

return ContentService.createTextOutput("success");

}

Web app code:

fetch(apiUri, {
  method: 'POST',
  body: {"selectedYear": 1998},
  headers: {
      'Content-Type': 'text/plain;charset=utf-8',
  } }).then(response => {
  console.log("success:", response);}).catch(err => {
  console.log("Error:" + err);

});

Error shown:

enter image description here

Hope can get some idea from here, thanks


Solution

  • In your showing script, how about the following modification?

    Google Apps Script:

    function doPost(e) {
      var params = JSON.parse(e.postData.contents);
      var selected = params.selectedYear;
      var ss = SpreadsheetApp.openById("1GeHldpOtB9CZAQjVZH66HJvPAAj7"); 
      var sheet = ss.getSheetByName("Sheet1");
      var lastRow = sheet.getLastRow();
      sheet.getRange(lastRow + 1, 1).setValue(selected);
      return ContentService.createTextOutput("success");
    }
    

    Javascript:

    const apiUri = "https://script.google.com/macros/s/###/exec"; // Please set your Web Apps URL.
    
    fetch(apiUri, {
      method: 'POST',
      body: JSON.stringify({ "selectedYear": 1998 }),
      headers: {
        'Content-Type': 'text/plain;charset=utf-8',
      }
    })
      .then(res => res.text())
      .then(response => {
        console.log("success:", response);
      }).catch(err => {
        console.log("Error:" + err);
      });
    
    • By this modification, when this modified Javascript is run, success: success is shown in the console. And, the value of 1998 is put into column "A" of "Sheet1".

    Note:

    References: