ThinkPHP6解决跨域问题 - 中间件设置
2022-11-24 11:10:29
218
{{single.collect_count}}

第一种方法

在前后端分离项目中,如通过ThinkPHP6开发api,涉及前端调用跨域问题,可通过自带的跨域中间件解决。
在 ./app/middleware.php 文件中启用内置中间件即可 

<?php// 全局中间件定义文件return [\think\middleware\AllowCrossDomain::class];
<?php// 全局中间件定义文件return [// 全局请求缓存// \think\middleware\CheckRequestCache::class,// 多语言加载// \think\middleware\LoadLangPack::class,// Session初始化// \think\middleware\SessionInit::class\think\middleware\AllowCrossDomain::class,];

等同于原生PHP中下面几行代码的效果。

<?phpheader('Content-Type: text/html;charset=utf-8');header('Access-Control-Allow-Origin:*'); header('Access-Control-Allow-Methods:POST,GET,OPTIONS,DELETE');header('Access-Control-Allow-Credentials: true');header('Access-Control-Allow-Headers: Content-Type,Content-Length,Accept-Encoding,X-Requested-with, Origin');

第二种方法 某个路由或分组支持跨域 参见 官方文档

跨域请求 :https://www.kancloud.cn/manual/thinkphp6_0/1037507

在路由上添加  ->allowCrossDomain() 即可

Route::get('new/:id', 'News/read')->ext('html')->allowCrossDomain();

回帖
全部回帖({{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 ? '加载中...' : '查看更多评论'}}