I have problem with my node.js API. I have API running on port 3000, and angular frontend with port 4200.
When i send request from angular to API, i have error with CORS. I tried three different solution, but still not working.
- First solution is install cors package, and add to code
app.use(cors());
- Second solution is add code below:
app.use((req, res, next) => { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); res.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS"); next(); })
- Last solution is add code below, with frontend url:
app.use(cors({ origin: 'http://frontend.com:4200' }));
None of the above worked, i.e. I still get an error with CORS all the time. When i send request from Postman, all works fine.
My actual code:
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const carRoutes = require('./routes/car');
const sequelize = require('./util/db');
const cors = require('cors');
sequelize.sync().catch(error => {
console.log(error);
});
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(cors());
app.use(carRoutes);
app.listen(3001);
Error message:
See Question&Answers more detail:osA request to a resource of another origin has been blocked: the "Same Origin Policy" policy does not allow remote resources to be loaded from "http://localhost:3000/car" (failed CORS request).