I am facing this issue:
Access to XMLHttpRequest at 'http://localhost:5000/api/surpactemp/' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.
On backend side I tried this way and didn't worked:
.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod()
I've been trying several ways to solve using Microsoft reference (below), but, no success so far. Also, I already tried not pass the headers object on Angular, then, I receive the error:
No 'Access-Control-Allow-Origin' header is present on the requested
Environment:
- Dotnet Core 3.1
- Angular 8
Backend: Startup.cs
//ConfigureServices
services.AddCors(options =>
{
options.AddPolicy(name: "CorsPolicy",
builder => builder.WithOrigins("http://localhost:4200")
.WithHeaders(HeaderNames.ContentType, "application/json")
.WithMethods("PUT", "DELETE", "GET", "OPTIONS", "POST")
);
});
//Configure
app.UseHttpsRedirection();
app.UseRouting();
app.UseCors("CorsPolicy");
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
Frontend: form-service.ts
httpOptions = {
headers: new HttpHeaders({
// 'Content-Type': 'application/json',
// 'withCredentials': 'false',
// 'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/json'
})
};
return this.httpClient.post('http://localhost:5000/api/surpactemp/', JSON.stringify(data.path), this.httpOptions);
Reference: https://learn.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-3.1#preflight-requests
UseCors
? It's position within the middleware pipeline setup is important.Startup.Configure
? Which other calls is it between? Middleware order is important, so it's possible you've got the order wrong.