简体   繁体   中英

Getting CORS using JS and Google Apps script

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM