
报错: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;
}以上就是thinkphp跨域报错的解决方案的详细内容,更多关于thinkphp跨域报错的资料请关注代码网其它相关文章!
发表评论