Angular 16调用Laravel 10 API时遭遇CORS错误求助
解决Angular调用Laravel 10 API的CORS问题
错误信息
Access to XMLHttpRequest at 'http://localhost:8000/api/v1/authenticate' from origin 'http://localhost:4201' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
解决方案
修正Laravel CORS配置文件
打开config/cors.php,调整以下配置项:return [ 'paths' => ['api/*', 'sanctum/csrf-cookie'], // 确保包含你的API路径 'allowed_origins' => ['http://localhost:4201'], // 直接指定前端地址,带凭证时不能用通配符 'allowed_methods' => ['GET', 'POST'], 'allowed_headers' => ['Origin', 'userKey', 'X-Requested-With', 'Content-Type', 'Accept', 'Authorization', 'enctype', 'X-Csrf-Token'], 'exposed_headers' => [], 'max_age' => 3600, 'supports_credentials' => true, // 开启凭证支持 ];移除手动添加的Header代码
删掉bootstrap/app.php中你之前添加的所有header()代码,这些代码会和Laravel自带的CORS中间件冲突,导致头部不生效。确认CORS中间件启用
在bootstrap/app.php的中间件配置中,确保api中间件组包含HandleCors中间件:->withMiddleware(function (Middleware $middleware) { $middleware->api([ \Illuminate\Http\Middleware\HandleCors::class, // 其他已存在的中间件 ]); })清除配置缓存并重启服务
执行以下命令刷新配置:php artisan config:clear php artisan serve
内容的提问来源于stack exchange,提问作者Ejaaz Khan
相关产品推荐
相关产品推荐

