THINKPHP跨域报错的解决方案
发布:smiling 来源: PHP粉丝网 添加日期:2024-04-20 18:39:08 浏览: 评论:0
这篇文章主要介绍了THINKPHP跨域报错has been blocked by CORS policy: Response to preflight request doesn't pass access control check的解决方案,文中通过代码示例给大家介绍的非常详细,需要的朋友可以参考下。
报错:has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
环境:thinkphp6 +nginx
今天和VUE配合调用接口的时候发现跨域报错。
按照官网给出的例子,在中间件配置允许跨域
- <?php
- // 中间件配置
- use think\middleware\AllowCrossDomain;
- return [
- AllowCrossDomain::class
- ];
前端请求偶尔还是会出现了跨域请求提示
Access to XMLHttpRequest at from origin has been blocked by CORS policy:
Request header field x-token is not allowed by
Access-Control-Allow-Headers in preflight response.
php在批量导入excel数据更新时偶尔会出现这个问题,出现时间不定,中间件都配置了跨域还是不行。
新建一个自定义的跨域中间件
- <?php
- namespace app\middleware;
- use think\middleware\AllowCrossDomain;
- class AllowCrossDomainMiddleware extends AllowCrossDomain
- {
- // 加入自定义请求头参数 X-Token
- 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',
- ];
- }
重新配置中间件
- <?php
- // 中间件配置
- use think\middleware\AllowCrossDomain;
- use app\middleware\AllowCrossDomainMiddleware;
- return [
- // 不使用默认的跨域中间件
- // AllowCrossDomain::class
- // 使用自定义跨域中间件
- AllowCrossDomainMiddleware::class
- ];
中间件,入口文件、路由都折腾了好几遍不行。
最后解决办法:
可以在入口文件添加以下代码,单独处理options请求
- public/index.php
- // 添加允许跨域请求头
- 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');
- // 处理 OPTIONS 请求
- if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
- exit;
- }
Tags: THINKPHP跨域报错
推荐文章
热门文章
最新评论文章
- 写给考虑创业的年轻程序员(10)
- PHP新手上路(一)(7)
- 惹恼程序员的十件事(5)
- PHP邮件发送例子,已测试成功(5)
- 致初学者:PHP比ASP优秀的七个理由(4)
- PHP会被淘汰吗?(4)
- PHP新手上路(四)(4)
- 如何去学习PHP?(2)
- 简单入门级php分页代码(2)
- php中邮箱email 电话等格式的验证(2)