Home>

I want to send the data entered in the contact form asynchronously to Google Sheets.
So, using Javascript fetch, send data via POST, execute GAS and write to spreadsheet
Created

But the process itself has been successfully written and the HTTP status code has returned 200
A CORS error has occurred during fetch processing, and it will be handled as an error.

So how can I get rid of the CORS error and proceed to the normal processing step
Also, is it often the case that an error occurs even with a status code of 200?
I would like you to tell me.

Error message
Access to fetch at 'API URL created by GAS' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
Applicable source code
ajaxButton.addEventListener ('click', function () {
let name = document.forms.google_form.name.value;
let hurigana = document.forms.google_form.hurigana.value;
let email = document.forms.google_form.email.value;
let msg = document.forms.google_form.msg.value;
const params = new URLSearchParams ();
params.set ('name', name);
params.set ('hurigana', hurigana);
params.set ('email', email);
params.set ('msg', msg);
const url = "API URL created with GAS";
const headers = new Headers ({
  'Content-Type': 'application/x-www-form-urlencoded',
})
const data = {
  method: 'POST',
  headers: headers,
  body: params,
  mode: "cors"
}
debugger;
 fetch (url, data)
 .then (function (response) {
   if (response.ok) {
      console.log ('Completed successfully');
    }
 })
 .catch (function (error) {
   console.log (error.message);
   console.log (error.stack);
 })
});
function doPost (e) {
  var ss = SpreadsheetApp.openById ('URL where the sheet exists');
  var sheet = ss.getSheetByName ("Sheet 1");
  var name = e.parameter.name;
  var hurigana = e.parameter.hurigana;
  var email = e.parameter.email;
  var msg = e.parameter.msg;
  // data entry
  sheet.appendRow ([name, hurigana, email, msg]);

When mode is set to no-cors, the process ends normally but an empty response is returned
The contents could not be confirmed by processing of .then.

  • Answer # 1

    Please check "CORS" and "Access-Control-Allow-Origin", but it ends with a brief description of the cause of the error and how to deal with it.

    The reason for the error is that there is noAccess-Control-Allow-Originin the response header of the API.
    In JavaScript, for security reasons, it is not possible to get a response without permission.
    By the way, if HTML and API are the same origin, this header is unnecessary, so in that case you don't need to worry too much.

    It cannot be handled by JavaScript alone, and the API side should specify the header ofAccess-Control-Allow-Originappropriately, or move HTML and API to the same origin Is necessary.