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
.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-OriginYou 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]
UPDATE
Since you are using
UseHttpsRedirection
, and why it is still usinghttp://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.
2. Use below cors setting.
3. Change the middleware order like below.
The cors issue should be fixed by applying the changes above.
PREVIOUS
You can’t use
WithOrigins
andSetIsOriginAllowed
together.The following code is an example of a correct CORS setup.
1. Allow All.
2. Allow specific Origin.
Here is related link: SignalR Cross Domain