1,环境:ngxin+thinkphp5.1
2,问题:使用ajax请求时报错
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. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
3,解决:查看thinkphp5.1文档
https://www.kancloud.cn/manual/thinkphp5_1/489844
4,出现新的报错
has been blocked by CORS policy: Request header field x-os is not allowed by Access-Control-Allow-Headers in preflight response.
5,解决
----------------------------------------------分割线-----------------------------------------------------
2019-10-18 更新,知道了一种新的方法
1,在项目的 application/common/behavior 目录下创建 "行为" 文件,在行为文件的run方法里,写相关逻辑
use think\Request;
use think\Response;
public function run(Request $request, $params){
$refer = $_SERVER['HTTP_REFERER'] ??'';
//这里的逻辑根据需求自己写,在接收到请求的时候会先走这里
if(! empty($refer) && parse_url($refer, PHP_URL_HOST) == '需要跨域的域名') {
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, PUT, OPTIONS, DELETE'); //支持的http 动作
header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, x-access-sign, x-access-time, uid');
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') Response::create()->contentType("application/json")->code(200)->send();
}
}
2,在模块的目录下创建 "tags.php" 文件
// 应用行为扩展定义文件
return [
// 应用初始化
'app_init' => [],
// 应用开始
'app_begin' => ['app\\common\\behavior\\Sign'], //注册行为
// 模块初始化
'module_init' => [],
// 操作开始执行
'action_begin' => [],
// 视图内容过滤
'view_filter' => [],
// 日志写入
'log_write' => [],
// 应用结束
'app_end' => [],
];
3,关于上面提到的 "行为","tags.php",请看官方文档,在文档页面上搜索这两个关键词就能找到