I'm making a request with pure javascript for a Minimal API in .NET 6, but when I open it in the browser I get the following message:
Access to fetch at 'https://localhost:7252/v1/todos' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
I've already added the CORS configuration in the API but it didn't work:
fetch('https://localhost:7252/v1/todos')
.then(response => response.json()) ...
builder.Services.AddCors(options => options.AddDefaultPolicy(builder =>
{
builder.WithOrigins(
"https://localhost:7252/v1/todos",
"https://localhost:7252");
}));
app.UseCors();
You may want to extend it a little
app.UseCors(builder => builder
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
here a full code sample
public class Startup
{
readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy(name: MyAllowSpecificOrigins,
builder =>
{
builder.WithOrigins("http://example.com",
"http://www.contoso.com");
});
});
// services.AddResponseCaching();
services.AddControllers();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseCors(MyAllowSpecificOrigins);
// app.UseResponseCaching();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}