java – Angular 5:预检的响应具有无效的HTTP状态代码403
作者:互联网
当我向服务器发送POST请求时,我收到一个错误:
Failed to load http://localhost:8181/test: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. The response had HTTP status code 403.
后端是用Java Spring编写的.
我创建测试的方法:
createTest() {
const body = JSON.stringify({
'description': 'grtogjoritjhio',
'passingTime': 30,
'title': 'hoijyhoit'
});
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Accept': 'application/json'
}
)
};
return this._http.post(`${this._config.API_URLS.test}`, body, httpOptions)
.subscribe(res => {
console.log(res );
}, error => {
console.log(error);
});
}
Get方法有效,但Post没有.他们都在Swagger和Postman工作.我多次更改了POST方法.我的代码中的标题不起作用,但我解决了他们扩展到谷歌浏览器的问题.只有一个错误:
Response for preflight has invalid HTTP status code 403.
在我看来,这不是角度问题.请告诉我我或我的朋友(编写后端)如何解决这个问题.
解决方法:
问题:
对于任何Cross-Origin POST请求,浏览器将首先尝试进行OPTIONS调用,当且仅当该调用成功时,它才会进行真正的POST调用.但在您的情况下,OPTIONS调用失败,因为没有’Access-Control-Allow-Origin’响应头.因此实际的呼叫将不会完成.
SLOUTION:
因此,要使其工作,您需要在服务器端添加CORS配置以设置Cross-Origin请求所需的相应头,如:
> response.setHeader(“Access-Control-Allow-Credentials”,“true”);
> response.setHeader(“Access-Control-Allow-Headers”,“content-type,if-none-match”);
> response.setHeader(“Access-Control-Allow-Methods”,“POST,GET,OPTIONS”);
> response.setHeader(“Access-Control-Allow-Origin”,“*”);
> response.setHeader(“Access-Control-Max-Age”,“3600”);
标签:java,spring,cors,http-status-code-403,angular5 来源: https://codeday.me/bug/20190724/1521661.html