Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular $http.post returnd empty error

I am using angular JS to send some data to nodejs server.

When I use, curl, I get back the data I send (correct result):

curl -d '{"MyKey":"My Value"}' -H "Content-Type: application/json" 'http://127.0.0.1:3000/s?table=register_rings&uid=1'
> {"MyKey":"My Value"}

However, when I use angularjs service, error occures.

.factory('RegisterRingsService', function($http, $q) {
    // send POST request with data and alert received
    function send(data, uid) {

  $http({
            method: 'POST',
            url: 'http://127.0.0.1:3000/s?table=register_rings&uid=1',
            data: '{"MyKey":"My Value"}',
            headers: { "Content-Type": "application/json", "Access-Control-Allow-Origin":"*"},
            responseType: 'json'
        }).success(function(data, status, headers, config) {
            alert('success', data, status);
        }).error(function(data, status, headers, config) {
            alert('error' + JSON.stringify(data) + JSON.stringify(status));
        }).catch(function(error){
            alert('catch' + JSON.stringify(error));
        });
}   

return  {send : send};  
  })

The error is following:

{"data":null,"status":0,"config":{"method":"POST","transformRequest":[null],"transformResponse":[null],"url":"http://127.0.0.1:3000/s?table=register_rings","data":"{\"MyKey\":\"My Value\"}","headers":{"Content-Type":"application/json","Access-Control-Allow-Origin":"*","Accept":"application/json, text/plain, */*"},"responseType":"json"},"statusText":""}

I suspect that I should insert CORS headers, but I am not sure how to do that.

Any help would be appreciated

like image 464
Zbynek Avatar asked Sep 13 '26 22:09

Zbynek


1 Answers

The problem is how you are transmitting the data over to server. This is because jQuery and Angular serialize the data differently.

By default, jQuery transmits data using Content-Type: x-www-form-urlencoded and the familiar foo=bar&baz=moe serialization. AngularJS, however, transmits data using Content-Type: application/json and { "foo": "bar", "baz": "moe" } JSON serialization, which unfortunately some Web server languages — notably PHP — do not unserialize natively.

To workaround this AngularJS developers provided hooks into the $http service to let us impose x-www-form-urlencoded.

$http({
   method  :'POST',
   url:'...',
   data: data, // pass in data as strings
   headers :{'Content-Type':'application/x-www-form-urlencoded'} // set the headers so angular passing info as form data (not request payload)
});

Please read this post for a working solution:

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

like image 148
Endre Simo Avatar answered Sep 16 '26 12:09

Endre Simo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!