在.net Core Web API和angular 6中启用CORS [英] Enabling CORS in .net core Web api and angular 6

查看:59
本文介绍了在.net Core Web API和angular 6中启用CORS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里,我正在使用来自Angular 6的HTTP POST请求,并且它在.net核心Web API调用中起作用,但是我没有将响应输出返回到Angular 6,并且在控制台中出现了一个错误,该错误是:

Here I'm using an HTTP POST request from Angular 6 and it is hitting in the .net core Web API call, but I'm not getting the response output back to Angular 6 and in console got an error that:

通过' http://localhost:55654/api/login/auth 来自来源" http://localhost:4200 "已被CORS政策阻止: 请求中不存在"Access-Control-Allow-Origin"标头 资源."

"Access to XMLHttpRequest at 'http://localhost:55654/api/login/auth' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource."

但是我有点困惑,如果它有任何CORS启用访问问题,它将不会打到Web API调用.但这击中了API调用,但我没有得到响应.

But I'm a bit confused that if it is any CORS enabling access issue, it won't hit the web API call. But it hits the API call and I'm not getting the response back.

Angular 6 HTTP POST请求:

this.http.post("http://localhost:55654/api/login/auth", credentials, {
  headers: new HttpHeaders({
 "Content-Type": "application/json"
      })
  }).subscribe(response => {
      let token = (<any>response);
      localStorage.setItem("jwt", token);
    }, err => {

    });

我已通过.NetCore Web API

Configure Startup.cs中的方法:

...
app.UseCors(options =>
  options.WithOrigins("http://localhost:4200")
    .AllowAnyMethod()
    .AllowAnyHeader());
 ...

ConfigureServices Startup.cs中的方法:

...
services.AddCors();
...

推荐答案

在Startup.cs上,添加ConfigureServices:

On Startup.cs add in ConfigureServices:

services.AddCors();

在配置"上添加

app.UseCors(x => x.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());

这解决了您的问题

这篇关于在.net Core Web API和angular 6中启用CORS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆