0

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)).

Pranay
  • 432
  • 4
  • 14
  • 1
    You need to understand what CORS is. https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS – SLaks Mar 14 '19 at 19:18
  • You are able to call the server because nothing in the web security model blocks your code from sending the request, and nothing in the CORS protocol causes the server to block the request. So the server gets the request and sends a response but the default same-origin policy that’s the basis of the web-security model requires the browser to block your frontend JavaScript from accessing the response — unless the response includes the Access-Control-Allow-Origin header. So that’s why even though the browser gets the response and you can see it in devtools, you can’t it from your frontend code. – sideshowbarker Mar 15 '19 at 12:29

1 Answers1

0

According to this: https://expressjs.com/en/resources/middleware/cors.html

var express = require('express')
var cors = require('cors')
var app = express()

app.use(cors())

should be enough

Pavel Kostenko
  • 1,859
  • 1
  • 18
  • 18