Laravel API对接Angular时遇「Multiple CORS header」错误的解决
我用Laravel开发的API在Postman中调用正常,但用Angular开发前端时,每次发送请求都会触发跨域错误:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost/master-fullstack/api-rest-laravel/public/api/user/update. (Reason: Multiple CORS header ‘Access-Control-Allow-Origin’ not allowed).
已尝试的配置
Laravel端跨域设置
在Laravel项目根目录的index.php中添加了跨域响应头:
header('Access-Control-Allow-Origin: *'); header("Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method, Authorization"); header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE"); header("Allow: GET, POST, OPTIONS, PUT, DELETE");
Angular前端请求代码
user.service.ts中的用户更新请求逻辑:
update(token: string, user: any) { let json = JSON.stringify(user); let params = "json="+json; let headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded').set('Authorization', token); return this._http.put(this.url + 'user/update', params, {headers: headers}); }
问题卡点
明明只配置了一个Access-Control-Allow-Origin头,却被提示存在多个;如果移除这个头,又会出现CORS header ‘Access-Control-Allow-Origin’ missing的错误。尝试将通配符*替换为Angular的本地地址http://localhost:4200,问题仍然存在。
最终解决方法
需要在Apache的httpd.conf配置文件中添加以下内容:
<IfModule mod_headers.c> Header set Access-Control-Allow-Origin "*" </IfModule>
然后启用Apache的headers模块(WampServer环境下操作路径:WampServer -> Apache -> Apache Modules -> 勾选headers_module)。
内容的提问来源于stack exchange,提问作者Adrian2895

