0

Caveat: I am a front-end developer, I don't have much experience with servers.

I'm building an app with Angular 1.2 that pings an API on a different subdomain. The backend dev on the project is using nginx and has set it up to allow cross-domain requests by essentially forwarding the subdomain, or something similar, I believe. I can do an $http.get request just fine, but when I try $http.post I get the Access-Control-Allow-Origin error.

Here's the kicker: I can make the same request with jQuery's $.ajax and it works just fine.

$.ajax({
    type: 'POST',
    url: 'http://api.mydomain.com/v1/customer/',
    data: theData,
    contentType: 'application/x-www-form-urlencoded',
    //contentType: 'text/plain',
    //crossDomain: true,
    success: function(){
        console.log("sent data via jquery");
    }
});

Here's how I have Angular set up:

var myServices = angular.module("myServices", []);

myServices.config(function($httpProvider) {
    $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
});

And:

    save: function(payload){
        console.dir($http);
        return $http.post('http://api.mydomain.com/v1/customer/', payload).then(function(result){
            return result;
        });
    },

What am I missing?

BenMorel
  • 34,448
  • 50
  • 182
  • 322
  • Looks like a dupe: http://stackoverflow.com/questions/16661032/http-get-is-not-allowed-by-access-control-allow-origin-but-ajax-is – Jason Sep 23 '13 at 20:56

3 Answers3

1

Pretty close, I see you're using .then(), so just follow the promise return pattern and pick it up in your controller:

return $http.post('http://api.mydomain.com/v1/customer/', payload).then(function(result){
    return result.data;
});

And your controller (I dont know what your service is called, replace TestService with the name):

TestService.save(param).then(function(data) {
    console.log(data); //Hello data!
});
tymeJV
  • 103,943
  • 14
  • 161
  • 157
1

Found the answer here:

http://victorblog.com/2012/12/20/make-angularjs-http-service-behave-like-jquery-ajax/

Angular sends serialized JSON, jQuery sends a query string.

  • Then you should accept your own answer, so that another people would find a solution quickly in the future. – Yang Sep 24 '13 at 10:30
0

It's likely a CORS related problem, specifically with the X-Requested-With header. See this post: How to load a cross-domain JSON with $http in angularjs 1.0.8 as it does with 1.2.0

Community
  • 1
  • 1
aet
  • 7,192
  • 3
  • 27
  • 25