User1063080413 posted
I am trying to figure out how to resolve a CORS issue.
I have an aspnetcore api that is running locally via iis express. its endpoint is:
http://localhost:2400/api
The api is exposed and can be accessed by postman, so I know it is there.
I have a react web app that is attempting to access the api. When started, it is at:
http://localhost:3000
There is a javascript fetch:
const baseUrl = 'http://localhost:2400/api/'
const url = 'contactRole/GetByContactId/'
const contactId = 'CE203B8B-323D-4E7E-8258-0460CC4D07FF'
const path = baseUrl + url + contactId;
const token = 'Bearer ' + accessToken;
console.log("token: " + token)
fetch(path, {
method: 'GET',
headers: {
authorization: 'Bearer' + accessToken
}
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => {
console.error("there has been a problem with your fetch operation", error)
})
This results in the following:
Access to fetch at 'http://localhost:2400/api/contactRole/GetByContactId/CE203B8B-323D-4E7E-8258-0460CC4D07FF' from origin 'http://localhost:3000' has been blocked by CORS policy: Request header field authorization is not allowed
by Access-Control-Allow-Headers in preflight response.
I have configured my api startup as follows:
readonly string MyAllowSpecificOrigins = "http://localhost:3000";
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(c =>
{
c.AddPolicy("AllowOrigin", options => options.WithOrigins(MyAllowSpecificOrigins));
});
and in the Configure:
app.UseRouting();
app.UseCors(options => options.AllowAnyOrigin());
app.UseAuthorization();
I don't understand why "options.AllowAnyOrigin()" is not enough.
What else must be done?