0

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.

2 Answers 2

2

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();
            }));
Sign up to request clarification or add additional context in comments.

2 Comments

Hi @Sergey, removing the trailing "/" in my existing code worked. But why that "/" was causing the issue?
If the URL terminates with /, the comparison of ulrs always returns false.
0

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();
                 });
        });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.