google-apps-scriptcors

How do i allow a CORS requests in my google script?


I want to post my contact form to my google script that will send an e-mail to me. I use the following code:

var TO_ADDRESS = "example@gmail.com"; // where to send form data

function doPost(e) {

  var callback = e.parameter.callback;

  try {
    Logger.log(e); // the Google Script version of console.log
    MailApp.sendEmail(TO_ADDRESS, "Contact Form Submitted",
                      JSON.stringify(e.parameters));
    // return json success results
    return ContentService
          .createTextOutput(callback+
          JSON.stringify({"result":"success",
                          "data": JSON.stringify(e.parameters) }))
          .setMimeType(ContentService.MimeType.JSON);
  } catch(error) { // if error return this
    Logger.log(error);
    return ContentService
          .createTextOutput(callback+JSON.stringify({"result":"error", 
          "error": e}))
          .setMimeType(ContentService.MimeType.JSON);
  }
}

When i try to post to the google script url, i get the following error:

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

I have no clue how to add the CORS-filter to my google script.

I know the script is working i have tested it with this plugin:

https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi


Solution

  • As far as I understood you have application to be run on custom domain. And it should access script on google cloud.

    The bad news: there are no way to skip CORS check on your application side(until request is simple that I believe is not your case).

    You should specify Access-Control-Allow-Origin on Google Cloud side:

    Cloud Storage allows you to set CORS configuration at the bucket level only. You can set the CORS configuration for a bucket using the gsutil command-line tool, the XML API, or the JSON API. For more information about setting CORS configuration on a bucket, see Configuring Cross-Origin Resource Sharing (CORS). For more information about CORS configuration elements, see Set Bucket CORS.

    You can use either of the following XML API request URLs to obtain a response from Cloud Storage that contains the CORS headers:

    storage.googleapis.com/[BUCKET_NAME]

    [BUCKET_NAME].storage.googleapis.com

    If this does not help for any reason you will need to get your own server working as a proxy:

    your client application <-> your backend that returns Access-Control-Allow-Origin <-> google cloud