ThinkPHP6解决跨域须用路由级allowCrossDomain()或自定义中间件精准控制,禁用header()随意设置;必须处理OPTIONS预检并动态匹配Origin白名单,带凭证时Access-Control-Allow-Origin不能为*且Nginx需透传Origin头。

如果您使用 ThinkPHP6.x 构建 API 后端,而 Vue 或 React 前端运行在独立域名或端口(如 http://localhost:8080),浏览器将因同源策略拦截请求,并提示 “No 'Access-Control-Allow-Origin' header is present”。以下是解决此问题的步骤:
一、使用 think-cors 官方扩展统一配置
该方法通过 Composer 引入官方维护的跨域中间件,自动处理 OPTIONS 预检、Credentials 兼容、Expose-Headers 等细节,避免手动 header() 被响应流程覆盖。
1、执行命令安装扩展:composer require topthink/think-cors
2、在 config/cors.php 中定义配置数组,确保包含 'origin' => ['http://localhost:8080', 'https://your-vue-domain.com'] 白名单
立即学习“PHP免费学习笔记(深入)”;
3、在 app/middleware.php 全局中间件列表中添加 \think\middleware\Cors::class
4、若前端携带 cookie 或 token 认证头,需将 'supportsCredentials' => true 设为 true,且 origin 不能为通配符 *
二、自定义中间件操作 Response 对象
该方法绕过框架默认响应生命周期干扰,直接在中间件 handle 方法中对 $next($request) 返回的 Response 实例调用 header() 方法注入 CORS 头,确保生效。
1、在 app/middleware/ 目录下新建 AllowCrossDomain.php 类文件
2、在 handle 方法中获取原始请求的 origin 头:$origin = $request->header('origin');
3、构造 header 数组,显式设置:'Access-Control-Allow-Origin' => $origin、'Access-Control-Allow-Credentials' => 'true'、'Access-Control-Allow-Methods' => 'GET, POST, PUT, DELETE, OPTIONS'
4、调用 return $next($request)->header($header); 并确保该中间件注册于路由分组或全局中间件首位
三、在入口文件 index.php 中注入响应头
该方法适用于调试阶段或轻量部署场景,不依赖中间件注册与配置加载顺序,直接在 HTTP 响应发出前强制写入头信息。
1、打开 public/index.php 文件,在 require __DIR__ . '/../vendor/autoload.php'; 之后插入代码块
2、添加判断逻辑:若请求 method 为 OPTIONS,立即返回空响应并终止流程:if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(200); exit(); }
3、设置基础跨域头:header('Access-Control-Allow-Origin: http://localhost:8080');
4、设置凭证与方法支持头:header('Access-Control-Allow-Credentials: true'); 和 header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
四、Apache 服务器层配置跨域响应头
该方法将跨域控制交由 Web 服务器处理,完全绕开 PHP 应用层,适用于生产环境 Nginx/Apache 反向代理部署场景,降低后端处理开销。
1、确认 Apache 已启用 headers_module 模块(通过 a2enmod headers 启用)
2、在站点配置文件或 .htaccess 中添加:Header set Access-Control-Allow-Origin "http://localhost:8080"
3、添加凭证支持:Header set Access-Control-Allow-Credentials "true"
4、允许指定请求头:Header set Access-Control-Allow-Headers "Content-Type, Authorization, X-Requested-With"
五、Vue/React 开发环境代理规避跨域
该方法仅作用于前端开发阶段,利用构建工具内置代理机制将 /api 请求重写至本地 ThinkPHP 服务地址,使浏览器认为请求同源,彻底避开 CORS 检查。
1、在 Vue CLI 项目中修改 vue.config.js,添加 devServer.proxy 配置项
2、配置目标地址为 ThinkPHP 后端:target: 'http://127.0.0.1:8000'
3、启用路径重写,去除请求前缀:pathRewrite: { '^/api': '' }
4、在 React 的 package.json 中添加 proxy 字段:"proxy": "http://127.0.0.1:8000"

















