原因
1、浏览器限制
2、跨域(域名,端口不一样都是跨域)
3、XHR(XMLHttpRequest请求)
同时满足三个条件才有可能产生跨域问题。
>利用钩子函数解决
1.在appcommonbehaviorCORS
代码语言:javascript复制<?php
namespace appcommonbehavior;
use thinkRequest;
use thinkResponse;
/**
* ${PARAM_DOC}
* @return ${TYPE_HINT}
* ${THROWS_DOC}
* Date: 2021/3/24 18:01
*/
class CORS{
public function run()
{
// 响应头设置 我们就是通过设置header来跨域的 这就主要代码了 定义行为只是为了前台每次请求都能走这段代码
$host_name = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : "*";
header("Access-Control-Allow-Origin:*");
header('Access-Control-Allow-Headers: content-type,token');
header('Access-Control-Allow-Methods:*');
header('Access-Control-Allow-Headers:token,Origin,X-Requested-With,Content-Type,content-type,Accept,Authorized-Token,Authori-zation,Authorization,authorized-token,If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since');
header('Access-Control-Allow-Credentials:false');
if (request()->isOptions()) {
exit();
}
}
}
2.将tags.php
代码语言:javascript复制return [
// 应用初始化
'app_init' => [],
// 应用开始
'app_begin' => [
'app\common\behavior\CORS'
],
// 模块初始化
'module_init' => [],
// 操作开始执行
'action_begin' => [],
// 视图内容过滤
'view_filter' => [],
// 日志写入
'log_write' => [],
// 应用结束
'app_end' => [
'app\common\behavior\CORS'
],
];
代码语言:javascript复制常见解决方法
if($_SERVER['REQUEST_METHOD'] == 'OPTIONS'){
header('Access-Control-Allow-Headers: content-type,token');
//允许的源域名
header("Access-Control-Allow-Origin:*");
//允许的请求头信息
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization");
//允许的请求类型
header('Access-Control-Allow-Methods: GET, POST, PUT,DELETE,OPTIONS,PATCH');
exit;
}