skip to Main Content

When calling my API with Postman it works, however, with my website it doesn’t. I got the console error below when I tried:

Access to XMLHttpRequest at ‘http://localhost:5243’ from origin
‘http://localhost:3000’ has been blocked by CORS policy: No
‘Access-Control-Allow-Origin’ header is present on the requested
resource. Unchecked runtime.lastError: A listener indicated an
asynchronous response by returning true, but the message channel
closed before a response was received

I modified the program.cs as explained in this post but didn’t work.

Below are the program.cs and memberadd.jsx code:

//Program.cs:

var policyName = "AllowLocalhost3000"; //
var builder = WebApplication.CreateBuilder(args);

// Add CORS policy to allow requests from 'http://localhost:3000'

builder.Services.AddCors(options => 
{ 
    options.AddPolicy(name: policyName, 
        policyBuilder => 
        { 
            policyBuilder.WithOrigins("http://localhost:3000") 
                         .AllowAnyHeader()  
                         .AllowAnyMethod()  
                         .AllowCredentials() 
                         .WithExposedHeaders("Access-Control-Allow-Origin", "http://localhost:3000")
                         .SetIsOriginAllowed((host) => true); 
        }); 
});

builder.Services.AddControllers();

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

var app = builder.Build();

app.UseCors(policyName);

if (app.Environment.IsDevelopment()) 
{ 
    app.UseSwagger(); 
    app.UseSwaggerUI(); 
}

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();


//MemberAdd.jsx:

try { 
    const response = await axios.post( 
        `http://localhost:5243/MemberFirstName=${encodeURIComponent(member.firstName)}&LastName=${encodeURIComponent(member.lastName)}&DOB=${encodeURIComponent(member.dob)}&email=${encodeURIComponent(member.email)}`
);

if (response.status === 200) {
    alert("Member Added!");
    clearForm();
  } else {
    alert("Failed to add member.");
  }
} catch (error) {
  console.error("Error adding member: ", error);
  alert("An error occurred while adding the member.");
}

2

Answers


  1. .WithExposedHeaders("Access-Control-Allow-Origin", "http://localhost:3000") is used to expose certain response headers to the client, but it’s not needed for setting Access-Control-Allow-Origin

    You should try to pass the data as a JSON object instead of query parameters for security reasons at most, but also to be more aligned with REST principles.

    one last thing, make sure the recipient method in the controller is decorated with [HttpPost]

    Login or Signup to reply.
  2. UPDATE

    Since you are using UseHttpsRedirection, and why it is still using http://localhost:5243 endpoint in cors error message.

    So please follow my suggestions below to check if it can fix the issue.

    1. Use https endpoint in your front-end.

    try { 
        const response = await axios.post( 
            `https://localhost:port/MemberFirstName=${encodeURIComponent(member.firstName)}&LastName=${encodeURIComponent(member.lastName)}&DOB=${encodeURIComponent(member.dob)}&email=${encodeURIComponent(member.email)}`
    );
    

    2. Use below cors setting.

    builder.Services.AddCors(options =>
    {
        options.AddPolicy(name: policyName,
            policyBuilder =>
            {
                policyBuilder.WithOrigins("http://localhost:3000")
                             .AllowAnyHeader()
                             .AllowAnyMethod()
                             .WithExposedHeaders("Access-Control-Allow-Origin", "http://localhost:3000")
                             .AllowCredentials();
            });
    });
    

    3. Change the middleware order like below.

    var app = builder.Build();
    
    if (app.Environment.IsDevelopment())
    {
        app.UseSwagger();
        app.UseSwaggerUI();
    }
    
    app.UseHttpsRedirection();
    
    app.UseCors(policyName);
    
    app.UseAuthorization();
    
    app.MapControllers();
    
    app.Run();
    

    The cors issue should be fixed by applying the changes above.

    PREVIOUS

    You can’t use WithOrigins and SetIsOriginAllowed together.

    The following code is an example of a correct CORS setup.

    1. Allow All.

    builder.Services.AddCors(options => options.AddPolicy("CorsPolicy", builder =>
    {
        builder.AllowAnyMethod()
            .SetIsOriginAllowed(_ => true)
            .AllowAnyHeader()
            .AllowCredentials();
    }));
    

    2. Allow specific Origin.

    builder.Services.AddCors(options => options.AddPolicy("CorsPolicy", policy =>
    {
        policy
            .WithOrigins("Your A site") 
            .AllowAnyMethod()
            .AllowAnyHeader()
            .AllowCredentials();
    }));
    

    Here is related link: SignalR Cross Domain

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search