在middleware文件夹下创建AllowCrossDomain.php
<?php
declare (strict_types=1);
namespace app\api\middleware;
use Closure;
use think\Request;
use think\Response;
use think\facade\Config;
/**
* 跨域请求支持
* 安全起见,只支持了配置中的域名
*/
class AllowCrossDomain
{
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' => 'think-lang, server, ba-user-token, batoken, Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-CSRF-TOKEN, X-Requested-With',
];
/**
* 跨域请求检测
* @access public
* @param Request $request
* @param Closure $next
* @param array|null $header
* @return Response
*/
public function handle(Request $request, Closure $next, ?array $header = []): Response
{
$header = !empty($header) ? array_merge($this->header, $header) : $this->header;
$origin = $request->header('origin');
if ($origin) {
$info = parse_url($origin);
// 获取跨域配置
$corsDomain = explode(',', Config::get('matter.cors_request_domain'));
$corsDomain[] = $request->host(true);
if (in_array("*", $corsDomain) || in_array($origin, $corsDomain) || (isset($info['host']) && in_array($info['host'], $corsDomain))) {
header("Access-Control-Allow-Origin: " . $origin);
}
}
return $next($request)->header($header);
}
}
在middleware.php中引入
<?php
return [
\app\api\middleware\AllowCrossDomain::class,
];
如不生效,可不使用上述方法,直接去修改入口文件
在入口文件public/index.php中添加options请求的处理
// 处理 OPTIONS 请求
if($_SERVER['REQUEST_METHOD'] == 'OPTIONS'){
header("'Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Token, 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; // 直接退出,不走后序流程
}