-1

I'm tring to POST a JSON data from my JavaScript to GoogleAppsScript but it gives me

Access to XMLHttpRequest at 'https://script.google.com/macros/s/AKfycbwnOTv_-kFISLa-3S-vkEqZscgrmptlf9nAP6o7O8vQm6exnvg/exec' from origin 'https://cdpn.io' 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.

First of all I tried to do the same with Postman And it Works:

enter image description here enter image description here

As you can see it even has access control allow origin * in answer headers. So why it doesn;t work with my JavaScript

This is Server Side (Google Apps Script)

function doPost(e){
  var params = e.parameter;
  var postData = JSON.parse(e.postData.contents);
  switch (postData.task) {
    case 'addRecord': var res = addRecord(postData.request);
  }
  var MyResponse = "It Works!";
  return ContentService.createTextOutput(MyResponse).setMimeType(ContentService.MimeType.JAVASCRIPT);
}

And this is my ClientSide (JavaScript):

var data = JSON.stringify({"task": 'addRecord', "request": {"first_name": "Oliver"}})
var request = new XMLHttpRequest();
var url = "https://script.google.com/macros/s/AKfycbwnOTv_-kFISLa-3S-vkEqZscgrmptlf9nAP6o7O8vQm6exnvg/exec";
request.open("POST", url, true);
request.setRequestHeader("Content-Type", "application/json");
request.send(data);
GhostKU
  • 1,898
  • 6
  • 23
  • 32
  • 1
    "As you can see it even has access control allow origin * in answer headers" — It has that in the response to the POST request. The error message says it doesn't have that in the response to the **preflight** request. – Quentin Aug 09 '19 at 09:15

1 Answers1

0

Simple requests don't trigger a CORS Pre-flight. As written in the documentation, To qualify as a simple request,

The only allowed values for the Content-Type header are:

application/x-www-form-urlencoded
multipart/form-data
text/plain

I just disabled sending Content-type and it works.

TheMaster
  • 45,448
  • 6
  • 62
  • 85
GhostKU
  • 1,898
  • 6
  • 23
  • 32