PHP接口允许H5页面ajax跨域访问设置方法
H5开发中使用ajax调用数据接口, 如果接口文件不在同域名下会提示跨域错误(No ‘Access-Control-Allow-Origin’ header is present on the requested resource.)。解决方法通过设置php接口文件的 Access-Control-Allow-Origin 头信息来实现跨域访问。// 1、允许单个域名访问header("Conte
·
H5开发中使用ajax调用数据接口, 如果接口文件不在同域名下会提示跨域错误(No ‘Access-Control-Allow-Origin’ header is present on the requested resource.)。
解决方法
通过设置php接口文件的 Access-Control-Allow-Origin 头信息来实现跨域访问。
// 1、允许单个域名访问
header("Content-type:application/json; charset=utf-8");
header("Access-Control-Allow-Origin:http://bm.tihu.com");
// 设置是否允许发送 cookies
header("Access-Control-Allow-Credentials:true");
header('Access-Control-Expose-Headers: *'); //服务器 headers 白名单,可以让客户端进行访问
header('Access-Control-Allow-Headers: *');
// 2、允许多个域名访问
header("Content-type:application/json; charset=utf-8");
$origin = isset($_SERVER['HTTP_ORIGIN'])? $_SERVER['HTTP_ORIGIN'] : '';
$allow_origin = array(
'http://client1.tihu.com',
'http://client2.tihu.com'
);
if(in_array($origin, $allow_origin)){
header('Access-Control-Allow-Origin:'.$origin);
}
header("Access-Control-Allow-Credentials:true");
// 3、允许所有域名访问
header('Access-Control-Allow-Origin:*');
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐

所有评论(0)