I am developing an desktop app using Electron, Angular and in Backend (API) node.js (express server).
node.js express server is running at http://localhost:3000 and angular wrapped inside electron is running at http://localhost:4200
When I am calling api end point /api/companies (httpget) from front end, I am able to call the end point and see the result via console.log in terminal window of server (nodemon server.js)
But the result is not given back from server to front end, and the error (Failed to load http://localhost:3000/api/companies: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.) is thrown in browser.
I have tried following code so far(commented and non-commented), but all not working:
// var originsWhitelist = [
// 'http://localhost:4200'
// ];
// var corsOptions = {
// origin: function (origin, callback) {
// var isWhitelisted = originsWhitelist.indexOf(origin) !== -1;
// callback(null, isWhitelisted);
// },
// credentials: true
// }
// app.use(cors());
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
Now my question is 1. why I am able to call the server end point when there is cors issue in first place and 2. why only cors issue surface while trying to send response back to client (res.json(data)).