Search code examples
angularjsweb-serviceshttp-request

AngularJS $http request to Web Service requires CORS


I am writing a service which needs to access a WebService (which I have no control over) - an API which I would like to consume in my application. I have visited the url in question within my browser and the login is successful, and I can see my access token, however when I try to use $http to visit the same page I get errors in the developer console in IE.

angular.module("app").factory("MyService", function($http){
    var serviceUrl = "http://some-web-page/service.asmx/";

    var logOn = function(username, password){
        var getUrl = serviceUrl + "logOn?username="+username+"&password="+password;
        $http.get(getUrl).then(
                function successCallback(response){
                    console.log("Success");
                    console.log(response);
                }, function errorCallback(response){
                    console.log("Error");
                    console.log(response);
                }
        );
    };

    return {
        logOn: logOn
    };
}).config(function($httpProvider){
    $httpProvider.defaults.useXDomain = true;
    delete $httpProvider.defaults.headers.common['X-Requested-With'];
});

and in the console I am getting

HTML1300: Navigation occurred.
File: home
HTML1503: Unexpected start tag.
File: home, Line: 5, Column: 1
SEC7118: XMLHttpRequest for http://some-web-page/service.asmx/logOn?username=username&password=password required Cross Origin Resource Sharing (CORS).
File: home
SEC7115: :visited and :link styles can only differ by colour. Some styles were not applied to :visited.
File: home

SEC7120: Origin http://localhost not found in Access-Control-Allow-Origin header.
File: home
SCRIPT7002: XMLHttpRequest: Network Error 0x80070005, Access is denied.

Solution

  • You cannot make a query to the remote server from your client side (regardless of which framework you are using, underneath it is all built on top of XMLHttpRequest) unless they enable and implement CORS on their side (server hosted at http://some-web-page/service.asmx/ ). You can make the request to your server and from your server to the remote server instead, however this is not always an ideal solution.