How to enable CORS between API and angular client

3.5k views Asked by At

We have been trying to set up CORS for a couple of days without success. It would be therefore very much appreciated to know how this is done once and for all. What we want to do is:

enter image description here

API server (only part of the server of course):

 // Config
 app.configure(function () {
   app.use(bodyParser.urlencoded({ extended: false }))
   app.use(bodyParser.json())    
   app.use(express.methodOverride());
   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();
   });
   app.use(express.static(path.join(application_root, "public")));
   app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
   app.use(app.router);
 });

Server for angular app (also only part of the setup):

 server.use(gzippo.staticGzip(__dirname + '/public'));
 server.set('view engine', 'ejs');

 // Environment
 var ENV = process.argv[2] || 'dev'; // prod or dev
 var port = process.env.PORT || 8080;

 // Single Page App (this route handles all other requests (catchall))
 server.all('/*', function(req, res, next) {
   res.set('Content-Type', 'text/html');
   res.render('index', includeFiles); // looks by default in views
 });

Angular config:

 app.config(['$locationProvider', '$httpProvider', '$urlRouterProvider', '$stateProvider',
    function($locationProvider, $httpProvider, $urlRouterProvider, $stateProvider) {

       ... Other stuff ...

       // enable CORS
       $httpProvider.defaults.useXDomain = true;
       delete $httpProvider.defaults.headers.common['X-Requested-With'];

       ...

    }
 ])

Currently when we do a request from angular:

 $http.post('http://<ip-address>:8889/signin', {email: '[email protected]', pass: '1234abcd'})
 .success(function(data) {
   console.log(data);
 });

we get the following error (on firefox):

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://<ip-address>/signin. (Reason: CORS preflight channel did not succeed).
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://<ip-address>:8889/signin. (Reason: CORS request failed).
1

There are 1 answers

3
patriques On

After some trial and error, we resorted to using the npm-module cors and things worked smothly.

Edits to API server:

// Config
app.configure(function () {
  app.use(bodyParser.urlencoded({ extended: false }))
  app.use(bodyParser.json())    
  app.use(express.methodOverride());
  app.use(cors());    // this was included
  app.use(express.static(path.join(application_root, "public")));
  app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
  app.use(app.router);
});

Angular config:

app.config(['$locationProvider', '$httpProvider', '$urlRouterProvider', '$stateProvider',
   function($locationProvider, $httpProvider, $urlRouterProvider, $stateProvider) {

      ... Other stuff ...

      // deleted these rows, since they are unnecessary
      // $httpProvider.defaults.useXDomain = true;
      // delete $httpProvider.defaults.headers.common['X-Requested-With'];

      ...

   }
])

And that was it! Hope it can help someone in the future.