Kevin Baker
Kevin Baker

Reputation: 1197

Http REST call problems No 'Access-Control-Allow-Origin' on POST

I have not been able to get Angular $http to communicate with a remote REST service. I have tried Restangular and $resource too. The problem seems to be with the underlying $http service and CORS limitations. I think I just need to get my headers right. Do I also need to tweak my server config?

I am getting the following error:

XMLHttpRequest cannot load http://www.EXAMPLE-DOMAIN.com/api/v2/users/sign_in. No 'Access-Control-    Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8100' is therefore not allowed access. 

I have researched this a lot. Currently I have tried setting the $httpProvider headings when configuring my app module and played with $http headers. Below is some of my current code.

My Service

app.service('Auth', function($http) {

        var headers = {
            'Access-Control-Allow-Origin' : '*',
            'Access-Control-Allow-Methods' : 'POST, GET, OPTIONS, PUT',
            'Content-Type': 'application/json',
            'Accept': 'application/json'
        };

        return $http({
            method: "POST",
            headers: headers,
      url: 'http://www.EXAMPLE-DOMAINcom/api/v2/users/sign_in',
            data: {"email":"[email protected]","password":"secret"}
    }).success(function(result) {
                console.log("Auth.signin.success!")
                console.log(result);
    }).error(function(data, status, headers, config) {
                console.log("Auth.signin.error!")
        console.log(data);
        console.log(status);
        console.log(headers);
        console.log(config);
    });

});

App Config

var app = angular.module('starter', ['ionic', 'app.controllers', $httpProvider])

    .config(['$httpProvider', function($httpProvider) {
        $httpProvider.defaults.useXDomain = true;
        $httpProvider.defaults.headers.common = 'Content-Type: application/json';
        delete $httpProvider.defaults.headers.common['X-Requested-With'];
    }
])

Upvotes: 2

Views: 18664

Answers (1)

rom99
rom99

Reputation: 799

If you are in control of the server, you might need to set the required headers there. Depending on which server, this might help: http://enable-cors.org/server.html

Upvotes: 3

Related Questions