This is not a duplication post,I know may be a part of the title asked many times in stackoverflow community, I checked all posts, and answers, but I think my problem and technologies which I used are different.
First of all I should mention ASP.NET Core WEB/API is my back-end-app and Reactjs is my front Application.
I read about CORS and I found out I must enable CORS on ASP.NET App and put 'Access-Control-Allow-Origin':'*' on my request's header, but I still have the below error while I call an api:
Actually we have two URL, one is the normal and the other one is the vanity url, vanity url is basically used as for redirection purpose. So when we use vanity url as both for api and front end it works but when the frontend and api are different we are getting CORS error, although we have added cors policy on server side code still we are getting the error when domains are different.
Tried almost every solution present on stackoverflow.
Below is the error i am getting
Access to fetch at 'https://abc123.com/api/home/getLoggedInUser/' from origin 'https://xyz123.com' 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. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled
This is my Program.cs code related to CORS:
builder.Services.AddCors(options =>
{
options.AddPolicy( "CorsPolicy",
builder => builder.WithOrigins("http://localhost:3000"
, "https://abc123.COM"
, "https://abc123.com"
, "https://abc123com"
, "https://abc123.com"
, "https://xyz123.com"
, "https://xyz123.com"
, "https://xyz123.com"
, "https://xyz123.com")
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
});
builder.Services.AddHttpContextAccessor();
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddAuthentication(IISDefaults.AuthenticationScheme);
var app = builder.Build();
app.UseCors("CorsPolicy");
// Configure the HTTP request pipeline.
if (app.Environment.IsEnvironment("Local"))
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseDefaultFiles();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();
This is my React code
useEffect(() => {
fetch(url + "home/getLoggedInUser/"+window.TestingUser, {
credentials: "include",
mode: 'cors',
headers: {
"accepts": "application/json"
}
})
.then(res => res.json())
.then(result =>console.log(result))
}, [])
Thanks
===================
Op mentioned in the comment that the CORS issue didn't happen in local side, only happened after deploy to IIS in AWS server.