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

app/middleware.php

<?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.

原因是我们添加了自定义的请求头​​X-Token​​用来携带token,所以需要我们重新改造一下中间件

新建一个自定义的跨域中间件

app/middleware/AllowCrossDomainMiddleware.php

<?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',
];
}

重新配置中间件

app/middleware.php

<?php

// 中间件配置

use think\middleware\AllowCrossDomain;
use app\middleware\AllowCrossDomainMiddleware;

return [
// 不使用默认的跨域中间件
// AllowCrossDomain::class

// 使用自定义跨域中间件
AllowCrossDomainMiddleware::class
];

继续改进

查看请求日志发现,options请求会走一遍处理流程,有些需要权限校验的地方还会因为缺少参数而报错,这样肯定不行。

可以在入口文件添加以下代码,单独处理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; // 直接退出,不走后序流程
}