4
votes

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 = "[email protected]"; // 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

4
where is your script expecting to be run? I believe currently you run it from localhost for development purposes. but how do you plan use it in the future?skyboyer
The script runs in the google cloud, my application runs on localhost. It is a school assignment.Joost Kaal
according to error message your script running at localhost is trying to access google cloud. But you say script should be run on google cloud. Am I missing something?skyboyer
The script runs on google cloud, and gets called by my angular application.Joost Kaal
sou CORS affects your angular application. where will it be run finally? there are different solutions possible depending on if it will run also at cloud,skyboyer

4 Answers

0
votes

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

2
votes

Late answer, but totally working...

To pass data from appscripts to another website, just use mime type JAVASCRIPT on appscripts side, like so:

doGet(e){   
 return ContentService
  .createTextOutput(e.parameter.callback + "(" + JSON.stringify(YOUR OBJECT DATA HERE)+ ")")
  .setMimeType(ContentService.MimeType.JAVASCRIPT);
}

And on the front end access it as:

<script>
var url = "https://script.google.com/macros/s/AKfy*****ACeR/exec?callback=loadData";
// Make an AJAX call to Google Script
jQuery.ajax({
crossDomain: true,
url: url,
method: "GET",
dataType: "jsonp"
});

 // log the returned data
  function loadData(e) {
  console.log(e);
  }
</script>

This works without any CROB/ CROS headache

0
votes

Well after several attempts, I was able to send the data through a web app form in angular 8. The solution is simple, within "HttpClient.post" you can enter a third parameter to establish an HTTP connection header this for "https://script.google.com" may not be correct and will end with an http connection failed by CORS security.

Just don't add the HTTP connection header as the third parameter of HttpClient.post

const object = {
  title: 'Prices',
  phone: '999999999',
  full_name: 'Jerson Antonio',
  email: '[email protected]',
  message: 'Hello, .......'
};
return this.http.post(this.API_REST_FORM, JSON.stringify(object));
0
votes

After several hours of CORS research, jsonp and other crazy attempts, this worked for me in order to consume a simple http endpoint provide by :

$.post('https://script.google.com/a/acme.org/macros/s/AKfy***A4B***eo/exec?token=myprecioustoken&operation=findAll', null).done(function(response) {
  console.log(response);
});

The rest of attempts, throw me this error:

Cross-Origin Request Blocked: The Same Origin Policy disallows
    reading the remote resource at
    https://script.google.com/a/utec.edu.pe/macros/s/AKfy***A4B***eo/exec?token=myprecioustoken&operation=findAll.
    (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

$.getJSON

$.getJSON('https://script.google.com/a/acme.org/macros/s/AKfy***A4B***eo/exec?token=myprecioustoken&operation=findAll', function(result) {
  console.log(result);
});

XMLHttpRequest

    var xmlhttp = new XMLHttpRequest();
    var theUrl = "https://script.google.com/a/acme.org/macros/s/AKfy***A4B***eo/exec?token=myprecioustoken&operation=findAll";
    xmlhttp.open("POST", theUrl);
    xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
    xmlhttp.send();