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?

1

3 Answers 3

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!
});
Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

Then you should accept your own answer, so that another people would find a solution quickly in the future.
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.