1、app目录下的middleware
添加:\app\middleware\AllowCrossDomainMiddleware::class,
<?php
// 全局中间件定义文件
return [
//全局跨域处理
\app\middleware\AllowCrossDomainMiddleware::class,
];
2、app目录下的middleware目录中,添加中间件,AllowCrossDomainMiddleware.php
<?php
declare (strict_types = 1);
namespace app\middleware;
use think\middleware\AllowCrossDomain;
use think\Response;
class AllowCrossDomainMiddleware
{
public function handle($request, \Closure $next) {
header('Access-Control-Allow-Origin: *');
header('Access-Control-Max-Age: 1800');
header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE');
header('Access-Control-Allow-Headers: Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-CSRF-TOKEN, X-Requested-With, Token');
return $next($request);
}
}
3.在入口文件public/index.php中加
// 处理 OPTIONS 请求
if($_SERVER['REQUEST_METHOD'] == 'OPTIONS'){
header("'Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Token, Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-CSRF-TOKEN, X-Requested-With, X-Token");
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS, PATCH');
exit; // 直接退出,不走后序流程
}