【发布时间】:2020-08-21 16:29:48
【问题描述】:
我正在实现一个 Angular 9 应用程序,它应该与 .NET Web api 通信。
Web api 在我的本地 IIS 10 上的 http://localhost:8080 或 http://localhost:44348 上发布,以便在我从 Visual Studio 调试时进行测试。
http.get 请求工作正常,但是当我执行 http.post 请求时,我收到以下错误:
Access to XMLHttpRequest at 'http://localhost:8080/api/Login/Post_User' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
但如果我尝试使用 Postman 进行发布请求,它工作正常。
这是我使用的代码 go 从我的 Angular 应用程序调用 web api:
this.apiService.post(this.user);
.....
public post(user){
return this.httpClient.post<any>(this.api_post_url, user).subscribe(data => {});
}
这是我的 web api 方法:
[HttpPost]
[ActionName("Post_User")]
public IHttpActionResult Post_User(User value)
{
// make insert in my database
return Ok();
}
...但是下面的“http.get”代码可以正常工作,我可以获取我的用户
this.profileUserService.getByEmail(this.user.email).pipe(
map((user: User) => {
return user;
})
).subscribe((data: User)=> {
if(data.name === undefined)
{
this.router.navigate(['/profile-user']);
}else{
this.router.navigate(['/profile-user']); //GO TO DASHBOARD
}
});
}
.....
public getByEmail(email: string){
this.url = `${this.api_get_url}` + email;
return this.httpClient.get(this.url)
}
我也尝试在我的 Angular 应用中实现代理,但结果相同
proxy.conf.json:
{
"/api/*": {
"target": "http://localhost:8080",
"secure": false,
"logLevel": "debug"
}
}
package.json:
...
"start": "ng serve --proxy-config proxy.conf.json",
...
最后是 angular.json
...
"proxyConfig": "src/proxy.conf.json"
...
提前感谢您的帮助。
【问题讨论】:
-
不要认为通配符在代理
/api/*上有效,你只需要/api -
您需要更改 .NET 端以启用 CORS。检查这是否对您有帮助:stackoverflow.com/questions/36270626/enablecors-for-vb-net
标签: angular rest api asp.net-web-api angular-services