thinkphp6 跨域问题
2022-11-24 11:10:29
193
{{single.collect_count}}

thinkphp6 跨域问题

https://blog.csdn.net/mouday/article/details/117781685

<?php/** * Created by PhpStorm. * User: wangkxin@foxmail.com * 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

<?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');
回帖
全部回帖({{commentCount}})
{{item.user.nickname}} {{item.user.group_title}} {{item.friend_time}}
{{item.content}}
{{item.comment_content_show ? '取消' : '回复'}} 删除
回帖
{{reply.user.nickname}} {{reply.user.group_title}} {{reply.friend_time}}
{{reply.content}}
{{reply.comment_content_show ? '取消' : '回复'}} 删除
回帖
收起
没有更多啦~
{{commentLoading ? '加载中...' : '查看更多评论'}}