Laravel与Angular跨域(CORS)请求问题排查求助
Laravel后端(Hostinger)与Angular前端(000webhost)CORS问题解决方案
问题概述
- 部署环境:Laravel后端托管于Hostinger,Angular前端托管于000webhost
- 异常现象:
LocationController:GET、POST、DELETE请求正常,PUT请求仍触发CORS错误LandController:所有非GET请求(POST/PUT/DELETE)均失败,浏览器提示:预检请求因重定向不被允许而被拦截
已尝试无效方案
- 在控制器方法中手动添加
Access-Control-Allow-Origin等响应头 - 配置独立的OPTIONS路由处理预检请求
- 集成Laravel CORS中间件(如
barryvdh/laravel-cors)
相关代码片段
LocationController PUT方法
public function update(Request $request, $id) { // 曾尝试手动添加响应头,无效 // return response()->json($updatedLocation, 200)->header('Access-Control-Allow-Origin', '*'); $location = Location::findOrFail($id); $location->fill($request->validated())->save(); return response()->json($location); }
LandController 路由配置(api.php)
Route::apiResource('/lands', LandController::class);
浏览器错误信息(LandController)
Access to XMLHttpRequest at 'https://your-hostinger-api-domain.com/api/lands/2' from origin 'https://your-000webhost-frontend.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.
针对性解决方案建议
1. 修正Laravel CORS全局配置
确保CORS中间件正确生效并覆盖所有API路由:
- 在
app/Http/Kernel.php的$middlewareGroups['api']中添加CORS中间件:'api' => [ \Barryvdh\Cors\HandleCors::class, // 若使用barryvdh/laravel-cors // 其他中间件... ], - 修改
config/cors.php配置:return [ 'paths' => ['api/*'], 'allowed_methods' => ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'], 'allowed_origins' => ['https://your-000webhost-frontend.com'], // 替换为实际前端域名 'allowed_origins_patterns' => [], 'allowed_headers' => ['*'], 'exposed_headers' => [], 'max_age' => 0, 'supports_credentials' => true, // 若前端请求带凭证(如Cookie)需开启 ]; - 执行缓存清理命令(Hostinger环境需通过SSH或控制面板终端运行):
php artisan config:cache php artisan route:cache
2. 排查并修复重定向问题(LandController专属)
预检请求不允许重定向,需排查以下点:
- 检查Hostinger的.htaccess规则:若有强制HTTPS或URL规范化的规则,需排除OPTIONS请求:
# 强制HTTPS,但跳过OPTIONS请求 RewriteCond %{REQUEST_METHOD} !OPTIONS RewriteCond %{HTTPS} !=on RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301] - 检查路由拼写与重定向:确认
LandController的路由无拼写错误,未被意外配置为重定向路由(如误写Route::redirect而非Route::put) - 检查请求URL格式:确保前端请求的URL末尾无多余斜杠(如
/api/lands/1/会触发后端301重定向到/api/lands/1,导致预检失败)
3. 定位LocationController PUT请求异常
- 检查请求头合规性:确认PUT请求的自定义头(如
Content-Type、Authorization)已被config/cors.php的allowed_headers包含 - 排除后端内部重定向:检查
update方法是否在返回响应前执行了redirect()操作 - 隔离测试:用Postman直接调用后端PUT接口,若正常则问题出在前端请求配置(如Angular的
HttpClient是否正确设置请求方法与头)
4. 前端配置校验
- 若后端开启
supports_credentials,Angular请求需添加withCredentials: true:this.http.put(`${apiUrl}/location/${id}`, data, { withCredentials: true }); - 确认前端请求的API域名与后端实际部署域名完全一致(避免HTTP/HTTPS混用、子域名错误)
内容的提问来源于stack exchange,提问作者ezaldeen alayed
相关产品推荐
相关产品推荐

