前后端联调遇CORS跨域问题:缺失Access-Control-Allow-Origin头
跨域请求拦截问题排查与解决
错误回顾
Access to XMLHttpRequest at 'http://test.localhost/login' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
排查与解决步骤
1. 确认CORS中间件已正确注册
自定义CORS中间件需完成注册才能生效,检查app/Http/Kernel.php:
- 全局生效:在
$middleware数组中添加中间件:protected $middleware = [ // ... 其他默认中间件 \App\Http\Middleware\Cors::class, ]; - 仅API路由生效:在
$middlewareGroups的api组中添加:protected $middlewareGroups = [ 'api' => [ // ... 其他默认中间件 \App\Http\Middleware\Cors::class, ], ]; - 单路由生效:先在
$routeMiddleware注册别名:
再给登录路由绑定中间件:protected $routeMiddleware = [ // ... 其他别名 'cors' => \App\Http\Middleware\Cors::class, ];Route::post('/login', [AuthController::class, 'login'])->middleware('cors');
2. 核对允许源与请求源的一致性
确保后端Access-Control-Allow-Origin设置的http://localhost:3000和前端实际origin完全匹配:
- 不要遗漏端口号(前端为3000,避免写成80)
- 严格区分
http和https协议 - 检查拼写错误,比如多余空格、域名写错
3. 改用Laravel自带CORS配置(Laravel 7+)
Laravel 7及以上版本自带CORS配置,自定义中间件可能和官方配置冲突,推荐用官方方案:
- 打开
config/cors.php修改配置:return [ 'paths' => ['/login', 'api/*'], // 包含登录路由 'allowed_methods' => ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'], 'allowed_origins' => ['http://localhost:3000'], 'allowed_headers' => ['Content-Type', 'Authorization'], 'max_age' => 0, 'supports_credentials' => false, ]; - 确认
app/Http/Kernel.php的api中间件组已包含\Illuminate\Http\Middleware\HandleCors::class(默认已存在) - 移除自定义的
Cors中间件,避免冲突
4. 清除缓存
修改配置或中间件后,必须清除Laravel缓存:
php artisan config:clear php artisan route:clear php artisan cache:clear
同时重启前端开发服务器、清除浏览器缓存,确保新配置生效
5. 检查服务器(Nginx/Apache)配置
如果后端用Nginx/Apache做反向代理,服务器可能拦截OPTIONS预检请求,需在服务器配置中添加CORS规则:
- Nginx示例:
location / { if ($request_method = OPTIONS) { add_header Access-Control-Allow-Origin http://localhost:3000; add_header Access-Control-Allow-Methods 'GET, POST, PUT, DELETE, OPTIONS'; add_header Access-Control-Allow-Headers 'Content-Type, Authorization'; return 204; } add_header Access-Control-Allow-Origin http://localhost:3000; add_header Access-Control-Allow-Methods 'GET, POST, PUT, DELETE, OPTIONS'; add_header Access-Control-Allow-Headers 'Content-Type, Authorization'; # ... 其他原有配置 } - 注意:服务器层面配置CORS头后,后端中间件不要再重复添加,避免头重复报错
内容的提问来源于stack exchange,提问作者chieeu.73
相关产品推荐
相关产品推荐

