https://blog.csdn.net/mouday/article/details/117781685
/**
* Created by PhpStorm.
* User: [email protected]
* Date: 2022/4/20
* Time: 14:05
*/
namespace app\middleware;
use think\middleware\AllowCrossDomain;
class AllowCrossDomainMiddleware extends AllowCrossDomain
{
protected $header = [
'Access-Control-Allow-Credentials' => 'true',
'Access-Control-Max-Age' => 1800,
'Access-Control-Allow-Methods' => 'GET, POST, PATCH, PUT, DELETE, OPTIONS',
'Access-Control-Allow-Headers' => 'Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-CSRF-TOKEN, X-Requested-With, X-Token',
];
}
全局中间件文件添加配置
app\middleware.php
// 全局中间件定义文件
use app\middleware\AllowCrossDomainMiddleware;
return [
// 全局请求缓存
// \think\middleware\CheckRequestCache::class,
// 多语言加载
// \think\middleware\LoadLangPack::class,
// Session初始化
\think\middleware\SessionInit::class,
AllowCrossDomainMiddleware::class,
];
OPTIONS文件的预检
新增文件到入口文件
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: 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; // 直接退出,不走后序流程
}
经过笔者测试
添加到对应模块的路由文件 app\api\route\api.php, 跨域解决
namespace app\api\route;
use think\facade\Route;
if($_SERVER['REQUEST_METHOD'] == 'OPTIONS'){
header("'Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Origin: *");
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, X-Token");
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS, PATCH');
exit; // 直接退出,不走后序流程
}
//测试路由
Route::GET('test','api/Index/index')->allowCrossDomain()->middleware('check');