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();
});
Put this line of code app.use(cors());
before routing code. (Assuming you have installed cors
package).