我正在Angular 2和Laravel 5.4中构建我的应用程序。 Angular2用于客户端,laravel 5.4用于服务器端。我在laravel中创建了API,并从Angular2中请求了这些API。
在Laravel中,我配置了Oauth 2护照服务,该服务正在验证所有API。在每个API调用中,我将在标题下面发送。
'内容类型','授权'
我如何使用标题调用API。
private headers = new Headers({'Content-Type': 'application/json', 'Authorization': 'Bearer ' + localStorage.getItem('access_token') });
let body = JSON.stringify({ user_id, company_id });
console.log(this.headers);
this.http.post(this.BuyerCostSetting, body, {headers:this.headers} )
.subscribe(
response => {
console.log('here');
console.log(response);
},
error => {
console.log(error.text());
}
);
当我从Angular2点击此API时,它显示以下错误:
Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response
答案 0 :(得分:17)
错误消息很明显,后端不允许'Authorization'
标头。
在后端Laravel应用程序中,您必须设置一个包含以下内容的响应头:
Access-Control-Allow-Headers : 'Content-Type', 'Authorization'
请在此处查看更多文档:https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Headers