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

18,643

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

Share:
18,643
Kevin Baker
Author by

Kevin Baker

Checkout my Linkedin account. http://linkedin.com/in/kevbaker

Updated on June 05, 2022

Comments

  • Kevin Baker
    Kevin Baker almost 2 years

    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'];
        }
    ])