ThinkPHP 6.0.16 跨域需通过自定义 Cors 中间件(首位注册、拦截 OPTIONS 并动态设 Origin 白名单)、路由级 allowCrossDomain()、控制器 response()->header() 或 Nginx 层配置四类方式解决,其中中间件最稳可靠。

ThinkPHP 6.0.16 默认不开启跨域支持,前端(如 Vue、UniApp、React)发起请求时若域名、协议或端口不同,浏览器会拦截并报错 No 'Access-Control-Allow-Origin' header。解决核心是让服务端在响应中正确返回 CORS 相关 HTTP 头,且必须覆盖预检(OPTIONS)请求。以下是实测有效的几种方式,按推荐度排序。
用自定义 Cors 中间件统一处理(最稳、推荐)
这是 TP6.0.16 最可靠的方式,能覆盖所有路由,避免 header 被框架覆盖,也兼容带 cookie 或 token 的复杂请求。
- 执行命令生成中间件:
php think make:middleware CorsMiddleware - 编辑
app/middleware/CorsMiddleware.php,完整替换handle方法:
<?php
namespace app\middleware;
use think\Request;
use think\Response;
use Closure;
class CorsMiddleware
{
public function handle(Request $request, Closure $next): Response
{
// 拦截 OPTIONS 预检请求,直接返回 204
if ($request->isOptions()) {
return response('', 204);
}
$response = $next($request);
// 动态获取 Origin,允许指定白名单或 localhost
$origin = $request->header('origin');
$allowedOrigins = ['https://your-fe.com', 'http://localhost:3000', 'http://127.0.0.1:8080'];
$accessOrigin = in_array($origin, $allowedOrigins) ? $origin : '*';
return $response->header([
'Access-Control-Allow-Origin' => $accessOrigin,
'Access-Control-Allow-Credentials' => 'true',
'Access-Control-Allow-Methods' => 'GET, POST, PUT, DELETE, OPTIONS',
'Access-Control-Allow-Headers' => 'Content-Type, Authorization, X-Requested-With, token'
]);
}
}
- 在
app/middleware.php全局中间件数组**首位**注册:\app\middleware\CorsMiddleware::class(确保它最先执行) - 注意:
Access-Control-Allow-Origin和Access-Control-Allow-Credentials: true必须同时存在且 Origin 不能为*,否则浏览器拒绝响应
路由级 allowCrossDomain()(适合局部接口)
只对某几个 API 路由生效,侵入性低,适合测试或灰度发布场景。
立即学习“PHP免费学习笔记(深入)”;
- 打开
route/app.php,在目标路由定义后链式调用:Route::post('/login', 'LoginController@login')->allowCrossDomain(['http://localhost:3000'], true); - 传入域名数组可允许多个来源;第二个参数
true表示启用凭证(即支持 Cookie 或 Authorization) - 该方法会自动处理 OPTIONS,无需额外写逻辑,但不适用于 console 命令或事件路由
控制器内手动设置 header(仅应急,慎用)
不推荐长期使用,容易因输出顺序或框架响应机制导致 header 失效(比如已输出内容后再设 header 会报错)。
- 必须用
response()->header(),不能用原生header()函数 - 示例:
return json(['code'=>0, 'msg'=>'ok'])->header('Access-Control-Allow-Origin', 'http://localhost:3000')->header('Access-Control-Allow-Credentials', 'true'); - 务必放在 return 语句最前,不能出现在 dump()、echo 或日志输出之后
Nginx 层配置(绕过 PHP,适合生产环境)
如果项目部署在 Nginx 上,可在服务器配置中统一加头,性能更好,也避免 PHP 层逻辑干扰。
- 在 server 或 location 块中添加:
add_header 'Access-Control-Allow-Origin' 'https://your-fe.com';
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'Content-Type, Authorization, X-Requested-With, token';
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Content-Type' 'text/plain; charset=UTF-8';
add_header 'Content-Length' 0;
return 204;
}
- 注意:Nginx 不会透传
Origin头给后端,若后端需动态判断来源(如多前端),仍建议用 PHP 中间件 - 重启 Nginx 生效:
nginx -s reload



















