Angular - Troubleshooting - FirstRun - CORS

Sample message

CORS error! Access to XMLHttpRequest at ‘http://localhost:26491/api/v1/policies‘ from origin ‘http://localhost:4200‘ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

Yuk! I hate this message. This is an error introduced by Microsoft (I guess) to help prevent programs from hacking into other programs. This message says that a process located at http://localhost:4200 is attempting to access http://localhost:26491/api/v1/policies. The web server blocked this thinking that it was an unauthorized attempt.

I say yuk because it’s hard to fix.

In fact I have code in my API class designed to fix this.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy("LocalAngular",
builder =>
{
builder.WithOrigins("*", "http://localhost:4200")
.AllowAnyHeader()
.AllowAnyMethod()
.AllowAnyOrigin();
});
});
:

more non related code follows.

I also have code in my configure function

1
2
3
4
5
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseCors("LocalAngular");
app.UseMvc();
}

This code worked until today. I think last week I did an update in my angular environment, I do not see that as the cause, but I can think of no other reason why this just started.

A reboot didn’t help.

Since I am in development mode, my api layer gives me a choice of running using IISExpress, or running the output of the API project directly. Usually I run in iisExpress.

I tried running the API layer directly, this didn’t help either. However, I like running this way, a console window opens and I get lots of information, including which SQL statements are being executed. I did need to tune my UI project to point to a new port.

After awhile I noticed, this dos window contains ‘info’ and ‘fail’ messages. One of my fail messages eluded to an incorrectly formatted property annotation. When I fixed the message the CORS error went away.

So a lesson learned is if the CORS error shows up out of the blue, suspect that this is a false message.

References