【问题标题】:Angular 7 Http Client and Asp Core - Cors errorAngular 7 Http 客户端和 Asp Core - Cors 错误
【发布时间】:2019-05-28 16:04:49
【问题描述】:

我在 Angular 7 中遇到了一个错误。我正在向 Asp Core API 发送一个传递对象的发布请求,该 API 响应 Ok() 和另一个对象。我的代码是这样的:

[HttpPost]
public async Task<IActionResult> UserRegistration(ViewModel viewModel){
    //Ignored code
    return Ok(someObject);
}

该操作(显然)工作得很好,它接受请求,解决任何必要的决定并完全按照我的需要返回对象。
现在让到 Angular 应用程序,我在 service.ts 中有一个方法,它调用api,以及component.ts 中的另一个使用第一种方法。他们是这样的:

//Service
userRegistration(model): Observable<any>{
  return this.http.post(url, model, httpOptions);
}

//Component
saveUser(model){
   this.myService.userRegistration(model).subscribe(
      data => {
         //do something
      },
      error => {
         //show message
      }
   );
}

这里的重点是Angular成功调用了Asp Core API,它将数据正确保存在数据库中,返回正确的对象,然后Angular出错:

CORS 策略已阻止从源“origin”访问“endpoint”处的 XMLHttpRequest:请求的资源上不存在“Access-Control-Allow-Origin”标头。

ERROR HttpErrorResponse {headers: HttpHeaders, status: 0, statusText: "Unknown Error", url: "URL", ok: false, ...}

如果 API 接受请求并正确响应,为什么会显示 CORS 错误?我该如何解决?

【问题讨论】:

  • 我已经回复here
  • 感谢@TonyNgo。我已经配置了cors,但是还是失败了
  • 您是否在 Angular、http 或 https 中使用正确的 url 协议到 web api?你能在启动时显示你的 CORS 配置吗?尝试使用WithOrigins 而不是AllowAnyOrigin.docs.microsoft.com/en-us/aspnet/core/security/…
  • @XingZou 你无法想象我的问题有多愚蠢。可耻的是,这只是浏览器缓存的问题。非常感谢。

标签: angular asp.net-core request httpclient angular7


【解决方案1】:

在后端的 startup.cs 中添加 CORS

  public void ConfigureServices(IServiceCollection services) 
  {
    services.AddMvc();
    services.Configure<MvcOptions>(options => {
      options.Filters.Add(new CorsAuthorizationFilterFactory("AllowMyOrigin"));
    });
  }

更多详情请关注article

【讨论】:

  • 谢谢!我已经在 Startup.cs 中配置了 cors,但错误仍然存​​在。
猜你喜欢
  • 2019-04-27
  • 1970-01-01
  • 2019-08-22
  • 2020-05-22
  • 2019-03-22
  • 2019-01-09
  • 1970-01-01
  • 2021-06-11
  • 1970-01-01
相关资源
最近更新 更多