SWIFTuser Studios

A small game development studio that works on sciency application too

Dealing with CORS/cross domain security exception

December 26
by anegri 26. December 2013 23:21

During an integration process with a web service using AngularJS and Chrome as a browser I tried almost every different way to consume a JSON web service.  What work best was to consume a web serivce through an angular service as follows:

 


'use strict';

 

myApp.factory('WebSrv', ['$http', '$timeout', function($http, $timeout) {

 

  return {

    get: function(callback) {

      $http.get('http://some-json-service.com',

        {transformResponse:function(data) {

 

           // transform becomes in handy 

            console.log("'" + data + "'");

            if (data != undefined && data != null && data != "") {

              return JSON.parse(data);

            }

            return [];

          }

        }

      )

      .success(function(data, status) {

        callback(data);

      })

      .error(function (data, status) {

        console.log('Service could not be reached ' + status);

      })

    }

  }

 

}]);


 

Once you have a proper connection to the web service and you are getting the CORS issue there are only three ways to fix it:

 

  1. Use a proxy from your server that reads the webservice and then feeds your web app the result (handle the errors on your side).
  2. Have the service use the right headers, this can be difficult as some developers will not modify their web serices with the requried headers, and will mention how their service works fine when they consume it on their own web apps hosted on the same server.
  3. Modify the target of the Chrome shurtcut to be as follows: "C:\<path to executable" --args --disable-web-service

The thrid option is not recomended and only good for special cases when testing, but you should really do 1 or 2 (if possible).