AngularJs $http.post() does not send data

前端 未结 30 1809
我在风中等你
我在风中等你 2020-11-22 02:51

Could anyone tell me why the following statement does not send the post data to the designated url? The url is called but on the server when I print $_POST - I get an empty

相关标签:
30条回答
  • 2020-11-22 03:31

    It's not super clear above, but if you are receiving the request in PHP you can use:

    $params = json_decode(file_get_contents('php://input'),true);

    To access an array in PHP from an AngularJS POST.

    0 讨论(0)
  • 2020-11-22 03:33

    To build on @felipe-miosso's answer:

    1. Download it as an AngularJS module from here,
    2. Install it
    3. Add it to your application:

      var app = angular.module('my_app', [ ... , 'httpPostFix']);
      
    0 讨论(0)
  • 2020-11-22 03:33

    This code solved the issue for me. It is an application-level solution:

    moduleName.config(['$httpProvider',
      function($httpProvider) {
        $httpProvider.defaults.transformRequest.push(function(data) {
            var requestStr;
            if (data) {
                data = JSON.parse(data);
                for (var key in data) {
                    if (requestStr) {
                        requestStr += "&" + key + "=" + data[key];
                    } else {
                        requestStr = key + "=" + data[key];
                    }
                }
            }
            return requestStr;
        });
        $httpProvider.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
      }
    ]);
    
    0 讨论(0)
  • 2020-11-22 03:34

    In my case I resolve the problem like this :

    var deferred = $q.defer();
    
    $http({
        method: 'POST',
        url: 'myUri', 
        data: $.param({ param1: 'blablabla', param2: JSON.stringify(objJSON) }),
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
    }).then(
        function(res) {
            console.log('succes !', res.data);
            deferred.resolve(res.data);
        },
        function(err) {
            console.log('error...', err);
            deferred.resolve(err);
        }
    );
    return deferred.promise;
    

    You need to use JSON.stringify for each param containing a JSON object, and then build your data object with "$.param" :-)

    NB : My "objJSON" is a JSON object containing array, integer, string and html content. His total size is >3500 characters.

    0 讨论(0)
  • 2020-11-22 03:35

    I had the same problem using asp.net MVC and found the solution here

    There is much confusion among newcomers to AngularJS as to why the $http service shorthand functions ($http.post(), etc.) don’t appear to be swappable with the jQuery equivalents (jQuery.post(), etc.)

    The difference is in how jQuery and AngularJS serialize and transmit the data. Fundamentally, the problem lies with your server language of choice being unable to understand AngularJS’s transmission natively ... 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.

    Works like a charm.

    CODE

    // Your app's root module...
    angular.module('MyModule', [], function($httpProvider) {
      // Use x-www-form-urlencoded Content-Type
      $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
    
      /**
       * The workhorse; converts an object to x-www-form-urlencoded serialization.
       * @param {Object} obj
       * @return {String}
       */ 
      var param = function(obj) {
        var query = '', name, value, fullSubName, subName, subValue, innerObj, i;
    
        for(name in obj) {
          value = obj[name];
    
          if(value instanceof Array) {
            for(i=0; i<value.length; ++i) {
              subValue = value[i];
              fullSubName = name + '[' + i + ']';
              innerObj = {};
              innerObj[fullSubName] = subValue;
              query += param(innerObj) + '&';
            }
          }
          else if(value instanceof Object) {
            for(subName in value) {
              subValue = value[subName];
              fullSubName = name + '[' + subName + ']';
              innerObj = {};
              innerObj[fullSubName] = subValue;
              query += param(innerObj) + '&';
            }
          }
          else if(value !== undefined && value !== null)
            query += encodeURIComponent(name) + '=' + encodeURIComponent(value) + '&';
        }
    
        return query.length ? query.substr(0, query.length - 1) : query;
      };
    
      // Override $http service's default transformRequest
      $httpProvider.defaults.transformRequest = [function(data) {
        return angular.isObject(data) && String(data) !== '[object File]' ? param(data) : data;
      }];
    });
    
    0 讨论(0)
  • 2020-11-22 03:35

    I like to use a function to convert objects to post params.

    myobject = {'one':'1','two':'2','three':'3'}
    
    Object.toparams = function ObjecttoParams(obj) {
        var p = [];
        for (var key in obj) {
            p.push(key + '=' + encodeURIComponent(obj[key]));
        }
        return p.join('&');
    };
    
    $http({
        method: 'POST',
        url: url,
        data: Object.toparams(myobject),
        headers: {'Content-Type': 'application/x-www-form-urlencoded'}
    })
    
    0 讨论(0)
提交回复
热议问题