-
Notifications
You must be signed in to change notification settings - Fork 77
Description
Hello!
I was going through the https://learn.microsoft.com/en-us/training/modules/build-web-api-minimal-spa/ module and I tried to connect provided client and API without proxy to test CORS configuration, but got "CORS missing allow origin" error.
Also Access-Control-Allow-Origin header was not present in the response.
First time I used code from the example in the module and it did not work:
// 2) define allowed domains, in this case "http://example.com" and "*" = all
// domains, for testing purposes only.
builder.Services.AddCors(options =>
{
options.AddPolicy(name: MyAllowSpecificOrigins,
builder =>
{
builder.WithOrigins(
"http://example.com",
"*"
);
});
});
I tried to add my localhost to the list but it was not working as well:
// 2) define allowed domains, in this case "http://example.com" and "*" = all
// domains, for testing purposes only.
builder.Services.AddCors(options =>
{
options.AddPolicy(name: MyAllowSpecificOrigins,
builder =>
{
builder.WithOrigins(
"http://example.com",
"http://localhost:3000/",
"*"
);
});
});
So I asked on Microsoft Q&A and was provided with a suggestion that helped:
// 2) define allowed domains, in this case "http://example.com" and "*" = all
// domains, for testing purposes only.
builder.Services.AddCors(options =>
{
options.AddPolicy(name: MyAllowSpecificOrigins,
builder =>
{
builder.WithOrigins(
"http://example.com",
"http://localhost:3000"
)
.AllowAnyHeader()
.AllowAnyMethod();
});
});
Initially I thought it was because .AllowAnyHeader().AllowAnyMethod(); methods calls, but next I was playing with the code and understood that the issue was bacause I added slash to the end "http://localhost:3000/".
So this code is working:
// 2) define allowed domains, in this case "http://example.com" and "*" = all
// domains, for testing purposes only.
builder.Services.AddCors(options =>
{
options.AddPolicy(name: MyAllowSpecificOrigins,
builder =>
{
builder.WithOrigins(
"http://example.com",
"http://localhost:3000"
);
});
});
Also I noticed that it works when asterisk is the only option:
// 2) define allowed domains, in this case "http://example.com" and "*" = all
// domains, for testing purposes only.
builder.Services.AddCors(options =>
{
options.AddPolicy(name: MyAllowSpecificOrigins,
builder =>
{
builder.WithOrigins(
"*"
);
});
});
And maybe worth mentioning that Access-Control-Allow-Origin header is returned only when calling client is in the list.
So I suggest updating code provided in the module examples and PizzaStore-Cors/Program.cs so other students do not get the issue.
Thank you!