THINKPHP跨域报错的解决方案

来自:网络
时间:2024-06-09
阅读:

THINKPHP跨域报错的解决方案

报错: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配合调用接口的时候发现跨域报错。

参考

跨域请求 · ThinkPHP5.1完全开发手册 · 看云

中间件 · ThinkPHP6.0完全开发手册 · 看云

按照官网给出的例子,在中间件配置允许跨域

<?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;
}

以上就是THINKPHP跨域报错的解决方案的详细内容,更多关于THINKPHP跨域报错的资料请关注其它相关文章!

返回顶部
顶部