'CORS Error while calling .Net WebAPI from Axios

I have a login form from where I am calling the .Net API from react using Axios

axios
.post(
    'https://localhost:5001/login',
    {
        email: '[email protected]',
        password: '12345',
    },
    {
        headers: {
            'Content-Type': 'application/json',
            'Access-Control-Allow-Origin': '*',
        },
    },
)
.then(function (response) {
    console.log(response)
})
.catch(function (error) {
    console.log(error)
})

Below is the code from Startup.cs to handle CORS on API side

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers();
    services.AddSwaggerGen(c =>
    {
        c.SwaggerDoc("v1", new OpenApiInfo { Title = "API", Version = "v1" });
    });
    services.AddCors(option => 
    {
        option.AddPolicy("CorsPolicy", policy =>
        {
            policy.AllowAnyMethod().AllowAnyHeader().WithOrigins("http://localhost:3000/");
        });
    }); 
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
        app.UseSwagger();
        app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "API v1"));
    }
    // app.UseHttpsRedirection();
    app.UseRouting();
    app.UseCors("CorsPolicy");
    app.UseAuthorization();
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
}

In browser's console I am getting these errors:

Access to XMLHttpRequest at 'https://localhost:5001/login' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Error: Network Error
    at createError (createError.js:16)
    at XMLHttpRequest.handleError (xhr.js:84)

POST https://localhost:5001/login net::ERR_FAILED

I have tested the API using REST Client extension of VS code. The API works properly but getting these errors when called from browser.



Solution 1:[1]

Try to move AddCors to the top of config section, before AddControllers. Also change the syntax and remove trailing "/" from an url:


services.AddCors(o => o.AddPolicy("CorsPolicy", builder =>
            {
                builder.WithOrigins("http://localhost:3000")
                       .AllowAnyMethod()
                       .AllowAnyHeader();
            }));

Solution 2:[2]

I faced the same issue. We started using the "withCredentials" options on axios to include the necessary cookies.

axios.defaults.withCredentials = true;

That broke the existing API calls even though we had used the AddCors option.

Turns out we were missing the AllowCredentials() option. This option allows cross-origin credentials to be sent to the server.

        services.AddCors(options =>
        {
            options.AddPolicy("AllowSpecificOrigins",
                 builder =>
                 {
                    builder
                        .SetIsOriginAllowedToAllowWildcardSubdomains()
                        .WithOrigins(                           
                            "https://*.mycorpdomain.com", 
                            )
                        .AllowAnyMethod()
                        .AllowAnyHeader()
                        .AllowCredentials();
                 });
        });

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Serge
Solution 2 BBC