Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cross-domain requests stopped working due to no `Access-Control-Allow-Origin` header present in the response

Tags:

I have an error reporting beacon I created using Google Apps script and it is published to run as myself and to be accessible to "anyone, even anonymous," which should mean that X-domain requests to GAS are allowed.

However, my browsers are now indicating there is no Access-Control-Allow-Origin header on the response after the code posts to the beacon.

Am I missing something here? This used to work as recently as two months ago. So long as the GAS was published for public access, then it was setting the Access-Control-Allow-Origin header.

In Google Apps Script:

Code.gs
function doPost(data){   if(data){         //Do Something   }   return ContentService.createTextOutput("{status:'okay'}", ContentService.MimeType.JSON); } 

Client Side:

script.js
$.post(beacon_url, data, null, "json"); 
like image 624
Joshua Dannemann Avatar asked Apr 08 '15 21:04

Joshua Dannemann


People also ask

How do I fix CORS policy no Access-Control allow origin?

If the server is under your control, add the origin of the requesting site to the set of domains permitted access by adding it to the Access-Control-Allow-Origin header's value. You can also configure a site to allow any site to access it by using the * wildcard. You should only use this for public APIs.

How do I fix cross origin request blocked?

Open a network tab in your console. In the response header look for the Access-Control-Allow-Origin header. If it does not exist then add it as a middleware in the way we discussed above. If it does exist then make sure there is no URL mismatch with the website.


1 Answers

When making calls to a contentservice script I always have sent a callback for JSONP. Since GAS does not support CORS this is the only reliable way to ensure your app doesn't break when x-domain issues arrive.

Making a call in jQuery just add "&callback=?". It will figure everything else out.

 var url = "https://script.google.com/macros/s/{YourProjectId}/exec?offset="+offset+"&baseDate="+baseDate+"&callback=?";  $.getJSON( url,function( returnValue ){...}); 

On the server side

function doGet(e){  var callback = e.parameter.callback;  //do stuff ...  return ContentService.createTextOutput(callback+'('+ JSON.stringify(returnValue)+')').setMimeType(ContentService.MimeType.JAVASCRIPT); } 
like image 80
Spencer Easton Avatar answered Oct 23 '22 14:10

Spencer Easton