由于响应中不存在“Access-Control-Allow-Origin"标头,跨域请求停止工作 [英] Cross-domain requests stopped working due to no `Access-Control-Allow-Origin` header present in the response

查看:16
本文介绍了由于响应中不存在“Access-Control-Allow-Origin"标头,跨域请求停止工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用 Google Apps 脚本创建的错误报告信标,它被发布为以我自己的身份运行,并且任何人,甚至是匿名的"都可以访问它.这应该意味着允许对 GAS 的 X 域请求.

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.

但是,在代码发布到信标后,我的浏览器现在显示响应中没有 Access-Control-Allow-Origin 标头.

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

我在这里遗漏了什么吗?这曾经在两个月前有效.只要发布 GAS 供公众访问,它就会设置Access-Control-Allow-Origin 标头.

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.

在 Google Apps 脚本中:

In Google Apps Script:

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

客户端:

$.post(beacon_url, data, null, "json");

推荐答案

在调用 contentservice 脚本时,我总是为 JSONP 发送回调.由于 GAS 不支持 CORS,这是确保您的应用在 x 域问题出现时不会中断的唯一可靠方法.

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.

在 jQuery 中进行调用只需添加&callback=?".它会解决所有其他问题.

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 ){...});

服务端

function doGet(e){
 var callback = e.parameter.callback;
 //do stuff ...
 return ContentService.createTextOutput(callback+'('+ JSON.stringify(returnValue)+')').setMimeType(ContentService.MimeType.JAVASCRIPT);
}

这篇关于由于响应中不存在“Access-Control-Allow-Origin"标头,跨域请求停止工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆