0
votes

Im using Google Apps Script, and Im just trying to connect from the javascript in the front end to the Google Script but I keep getting CORS errors.

Access to XMLHttpRequest at 'https://script.google.com/macros/s/KEY/exec' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

In the JS I have this

  var email = $('#ID_EMAIL').val();

    $.post("https://script.google.com/macros/s/KEY/exec",
        {
          email: email
        },
        function (data) {
            console.log("success");
        }, 'json');

and in the GAS

function doPost(e) {
  return "hello";
  }

I dont know why i keept getting the error if it just a basic code.

I have publish the google sheet as a web page, and the GAS as a web applications public to anyone.

I dont know what Im missing

1
Consider adding the header Access-Control-Allow-Origin * to the post request?evolutionxbox

1 Answers

1
votes

This was happening to me not to long ago, and it was driving me crazy. Hopefully I can spare you some of that pain. The ultimate problem (in my opinion) is that the error message is not actually helpful because it sends you down a CORS rabbit hole that is not actually useful.

For the doPost / doGet methods to work as expected, you have to return a ContentService object. So, if you change your doPost to something like the following, you should be good:

function doPost(e) {
  return ContentService.createTextOutput("hello");
  }

Alternatively, if you want to return a json:

return ContentService
    .createTextOutput(JSON.stringify({
      "result": "success",
      "success": "hello"
    }))
    .setMimeType(ContentService.MimeType.JSON);

Make sure to redeploy your webapp after making changes.

This doesn't appear to be the case for you, but, it's worth mentioning that if there is any fatal error in the google script web app, you will see that CORS error (at least in my experience). So for example, once upon a time, I was seeing that error because, although I was returning a ContentService object, I was calling a variable that I had not yet defined, so the script was erroring out before hitting the return statement.