gpt4 book ai didi

angular - 请求的资源上存在“Access-Control-Allow-Origin” header

转载 作者:行者123 更新时间:2023-12-01 21:44:17 25 4
gpt4 key购买 nike

我正在尝试从 Angular 应用程序连接到我的 .net 核心 API。当我尝试这样做时,我收到一条错误消息:

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

下面是来 self 的 Angular 应用程序的控制台消息:

enter image description here

这是我为解决错误所做的工作。我在 startup.cs 文件的 ConfigureServices 方法中添加了 services.addCors:

public void ConfigureServices(IServiceCollection services)
{

services.AddCors(options =>
{
options.AddPolicy("AllowAnyCorsPolicy", policy => policy.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin());
});

services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
services.AddControllers();
services.AddDbContext<db_recloadContext>();

}

在配置方法中,我输入了以下代码:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();

}
else
{
app.UseHsts();
}
app.UseCors("AllowAnyCorsPolicy");
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}

在我的 Controller 中,我有以下代码:

namespace RecLoad.Controllers
{
[Route("api/[controller]")]
[EnableCors("AllowAnyCorsPolicy")]
public class RecLoadPrimeController : ControllerBase
{
private readonly db_recloadContext _context;

public RecLoadPrimeController(db_recloadContext context)
{

_context = context;
}

我遵循了 Microsoft 文档和 stackoverflow 帖子之一中给出的说明:

https://stackoverflow.com/questions/42199757/enable-options-header-for-cors-on-net-core-web-api

和微软文章:

https://learn.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-3.1

我花了很多时间浏览其他文档并在 startup.cs 文件中尝试了不同的代码,但这个错误并没有消失。

下面是我运行良好的 api:

[HttpGet]
public ActionResult<string> Get()
{

return "This is a test";

}

下面是我的开发者工具的标题:

enter image description here

我还在我的 chrome 浏览器中启用了 CORS 扩展。下面是图片:

enter image description here

我们将不胜感激任何帮助。

最佳答案

要使其正常工作,您可以尝试以下操作:

1) 在ConfigureServices 方法中,调用AddCors 来配置CORS 服务,最初,允许任何来源:

services.AddCors(options => 
{
options.AddPolicy("AllowAnyCorsPolicy", policy => policy.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin());
});

2) 在 Configure 方法中添加 UseCors,这将中间件添加到 Web 应用程序管道:

app.UseRouting();
app.UseCors("AllowAnyCorsPolicy");
app.UseMvc();

由于 ASP.NET Core 3.1 .UseCors() 需要在 .UseRouting() 之后调用,如 https://github.com/dotnet/aspnetcore/issues/17830 中所述.

当此初始配置正常工作时,稍后可以根据您的要求进行修改。

关于angular - 请求的资源上存在“Access-Control-Allow-Origin” header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60924318/

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