Home > Blockchain >  cors-error although endpoint exists in policy
cors-error although endpoint exists in policy

Time:02-25

I have a pretty simple ASP.NET core-webapi that I'm trying to access from my client. The client is running on http://localhost:3000, while my server is running on https//localhost:7156. So I added a policy to accept requests from localhost:3000:

my Program.cs:

var builder = WebApplication.CreateBuilder(args);

// basic otel instrumentalisation
builder.Services.AddOpenTelemetryTracing(svc =>
{
    svc.AddSource(new[] { nameof(ServiceController), nameof(StressTestController), nameof(BoundaryPointsController), nameof(AaaServiceClient) }).
        SetResourceBuilder(ResourceBuilder.CreateDefault().AddService(serviceName: svcName, serviceVersion: svcVersion)).
        AddHttpClientInstrumentation().
        AddAspNetCoreInstrumentation();
}).AddCors(options =>
{
    options.AddDefaultPolicy(
        builder =>
        {
            builder.WithOrigins("https://localhost:3000",
                "http://localhost:3000", 
                "localhost:3000");
        });
});

builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();
app.UseHttpsRedirection();    
app.UseCors();     
app.UseAuthorization();    
app.MapControllers();    
app.Run();

my controller:

[EnableCors]
[ApiController]
[Route("api/projectdb/[action]")]
public class LoadDataController : ControllerBase
{
    [HttpPost, ActionName("load")]
    public async Task<ActionResult> LoadData() { ... }
}

When I perform the request from my client I get CORS-error:

const response = await fetch(`https://localhost:7156/api/projectdb/load`, {
        method: 'POST',
        body: '{ }',
        headers: {'Content-Type': 'application/json; charset=UTF-8'} 
    });

This is the error I get:

Access to fetch at 'https://localhost:7156/api/projectdb/load' from origin 'http://localhost:3000' has been blocked by CORS policy: Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response.

CodePudding user response:

The error message is on point: because of the value of your request's Content-Type header, you need to explicitly allow that header in your CORS configuration:

// -snip-
.AddCors(options =>
  options.AddDefaultPolicy(builder =>
    builder.WithOrigins("http://localhost:3000")
      .WithHeaders("Content-Type");
  )
);
  • Related