🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
``` <?php /** * Created by PhpStorm. * User: Administrator * Date: 2021/4/9 * Time: 17:51 */ declare (strict_types = 1); namespace app\middleware; use Closure; use think\Config; use think\Request; use think\Response; class AllowCrossDomain { protected $cookieDomain; // header头配置 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,token', ]; /** * AllowCrossDomain constructor. * @param Config $config */ public function __construct(Config $config) { $this->cookieDomain = $config->get('cookie.domain', ''); } /** * 允许跨域请求 * @access public * @param Request $request * @param Closure $next * @param array $header * @return Response */ public function handle($request, Closure $next, ?array $header = []) { $header = !empty($header) ? array_merge($this->header, $header) : $this->header; if (!isset($header['Access-Control-Allow-Origin'])) { $origin = $request->header('origin'); if ($origin && ('' == $this->cookieDomain || strpos($origin, $this->cookieDomain))) { $header['Access-Control-Allow-Origin'] = $origin; } else { $header['Access-Control-Allow-Origin'] = '*'; } } return $next($request)->header($header); } } ``` 在这里可以使用tp6的前置中间件 首先开启中间件的文件配置 ![](https://img-blog.csdnimg.cn/d2e2026f30374d06a0b96669e255f653.png?x-oss-process=image/watermark,type_ZHJvaWRzYW5zZmFsbGJhY2s,shadow_50,text_Q1NETiBAbG1wNTAyMw==,size_20,color_FFFFFF,t_70,g_se,x_16)