public /index.php文件下处理
//处理跨域Options预检请求
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
$origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '';
$allow_origin = [
'http://127.0.0.1:5500',
'http://127.0.0.1:5501',
'http://127.0.0.1:5502',
];
if (in_array($origin, $allow_origin)) {
//允许的源域名
header('Access-Control-Allow-Origin:' . $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;
}
第二步,处理正常请求的跨域
在基础控制器中加入如下代码即可
//控制器的初始化方法
protected function _initialize()
{
parent::_initialize();
$origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '';
$allow_origin = [
'http://127.0.0.1:5500',
'http://127.0.0.1:5501',
'http://127.0.0.1:5502',
];
if (in_array($origin, $allow_origin)) {
//允许的源域名
header('Access-Control-Allow-Origin:' . $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');
}
}
一般我是允许所有的域名访问
线上也是
//允许的源域名
header("Access-Control-Allow-Origin: *");
//允许的请求头信息
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization");
//允许的请求类型
header