gpt4 book ai didi

Angular 9 和 .NET Core - 从源 localhost :4200 has been blocked by CORS policy 访问

转载 作者:行者123 更新时间:2023-12-04 02:32:54 30 4
gpt4 key购买 nike

我在 Angular 9 中有应用程序,在 .NET Core 3.1 中有后端
当我想从 Angular 客户端发出请求时:

private httpHeaders: HttpHeaders;

constructor(private httpClient: HttpClient, @Inject('BASE_URL') private baseUrl: string) {
this.httpHeaders = new HttpHeaders({
'Access-Control-Allow-Origin': '*'
});
}

return this.httpClient.get<any>(`${environment.apiUrl}/findUser/GetUsers?name=${name}&lastname=${lastname}`, {
headers: this.httpHeaders,
reportProgress: true,
observe: 'events'
});
Startup.cs我的设置看起来像这样:
services.AddCors();
services.AddControllers();

app.UseCors(x => x
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
在 Controller 中:
[HttpGet]
[Route("getUsers")]
public IEnumerable<UserAccountDTO> GetUsers(string name, string lastname)
{}
但它不起作用:
  Access to XMLHttpRequest at 'http://localhost:20677/findUser/GetUsers?
name=&lastname=John' from origin 'http://localhost:4200' has been blocked by CORS
policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

这是请求:
GET /findUser/GetUsers?name=&lastname= HTTP/1.1
Host: localhost:20677
Connection: keep-alive
Access-Control-Allow-Origin: *
Accept: application/json
Authorization: Bearer xxxxxxxxxxxxxxx
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36
Content-Type: application/json
Origin: http://localhost:4200
Sec-Fetch-Site: same-site
Sec-Fetch-Mode: cors
Sec-Fetch-Dest: empty
Referer: http://localhost:4200/find-user
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9

最佳答案

我认为是,见the docs

// in ConfigureServices
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy(
name: "AllowOrigin",
builder =>{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
});
});
}

// in Configure
public void Configure(IApplicationBuilder app)
{
app.UseCors("AllowOrigin");
}
注意 :我在收到 ok 后更新了答案;我错过了 UseCors 中的双引号。

2021 年 4 月 17 日更新 app.UseCors("AllowOrigin");必须位于其他中间件的顶部。

关于Angular 9 和 .NET Core - 从源 localhost :4200 has been blocked by CORS policy 访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63165649/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com