No 'Access-Control-Allow-Origin' header is present.. angular 7 and express

13.6k Views Asked by At

I am running a server with express at port 3000 and a client with angular 7 at port 4200. Once I make a request, I run into CORS issue.

Access to XMLHttpRequest at 'http://localhost:3000/drug' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I have tried all the solutions online like using cors package, and setting the middleware before router like below codes (Angular 6 - No 'Access-Control-Allow-Origin' header is present on the requested resource). But it still is not solved and keep getting same errors. Does anyone have same problem that CORS is not solved with all the solutions? Could you please help me?

app.use((req, res, next) => {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");
  res.header(
    "Access-Control-Allow-Header",
    "Origin, X-Requested-With, Content-Type, Accept"
  );
  next();
});

app.use((req, res, next) => {
      res.header("Access-Control-Allow-Origin", "http://localhost:4200");
      res.header("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");
      res.header(
        "Access-Control-Allow-Header",
        "Origin, X-Requested-With, Content-Type, Accept"
      );
      next();
    });
2

There are 2 best solutions below

2
On

Put this line of code app.use(cors()); before routing code. (Assuming you have installed cors package).

0
On

I think answer would be so late, but for somebody in future:
You have to turn it on at the server side. I'm .Net developer, therefore I'll show in example of .Net core app. In startup file method ConfigureServices you should add next code

services.AddCors(options =>
        {
            options.AddPolicy("CorsPolicy",
                builder => builder.WithOrigins("http://localhost:4200")
                .AllowAnyMethod()
                .AllowAnyHeader()
                .AllowCredentials());
        });

After that you should edit method Configure. Add next line before calling UseMvc

app.UseCors("CorsPolicy");

That's all. I hope this answer will help to somebody.