AngularJs $http.post() does not send data

前端 未结 30 1753
我在风中等你
我在风中等你 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:26

    If using Angular >= 1.4, here's the cleanest solution using the serializer provided by Angular:

    angular.module('yourModule')
      .config(function ($httpProvider, $httpParamSerializerJQLikeProvider){
        $httpProvider.defaults.transformRequest.unshift($httpParamSerializerJQLikeProvider.$get());
        $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded; charset=utf-8';
    });
    

    And then you can simply do this anywhere in your app:

    $http({
      method: 'POST',
      url: '/requesturl',
      data: {
        param1: 'value1',
        param2: 'value2'
      }
    });
    

    And it will correctly serialize the data as param1=value1&param2=value2 and send it to /requesturl with the application/x-www-form-urlencoded; charset=utf-8 Content-Type header as it's normally expected with POST requests on endpoints.

    TL;DR

    During my research I found that the answer to this problem comes in many different flavors; some are very convoluted and depend on custom functions, some depend on jQuery and and some are incomplete in suggesting that you only need to set the header.

    If you just set the Content-Type header, the end point will see the POST data, but it won't be in the standard format because unless you provide a string as your data, or manually serialize your data object, it will all be serialized as JSON by default and may be incorrectly interpreted at the endpoint.

    e.g. if the correct serializer was not set in the above example, it would be seen in the endpoint as:

    {"param1":"value1","param2":"value2"}
    

    And that can lead to unexpected parsing, e.g. ASP.NET treats it as a null parameter name, with {"param1":"value1","param2":"value2"} as value; or Fiddler interprets it the other way, with {"param1":"value1","param2":"value2"} as the parameter name, and null as the value.

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

    this is probably a late answer but i think the most proper way is to use the same piece of code angular use when doing a "get" request using you $httpParamSerializer will have to inject it to your controller so you can simply do the following without having to use Jquery at all , $http.post(url,$httpParamSerializer({param:val}))

    app.controller('ctrl',function($scope,$http,$httpParamSerializer){
        $http.post(url,$httpParamSerializer({param:val,secondParam:secondVal}));
    }
    
    0 讨论(0)
  • 2020-11-22 03:28

    I had the same problem in express .. to resolve you have to use bodyparser to parse json objects before sending http requests ..

    app.use(bodyParser.json());
    
    0 讨论(0)
  • 2020-11-22 03:28

    Just updated from angular 1.2 to 1.3, have found a problem in the code. Transforming a resource will lead to an endless-loop because (I think) of the $promise holding again the same object. Maybe it will help someone...

    I could fix that by:

    [...]
      /**
     * 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;
    
    angular.forEach(obj, function(value, name) {
    +    if(name.indexOf("$promise") != -1) {
    +        return;
    +    }
    
        value = obj[name];
        if (value instanceof Array) {
            for (i = 0; i < value.length; ++i) {
    [...]
    
    0 讨论(0)
  • 2020-11-22 03:29

    I also faced similar problem and i was doing something like this and that didn't worked. My Spring controller was not able read data parameter.

    var paramsVal={data:'"id":"1"'};
      $http.post("Request URL",  {params: paramsVal});  
    

    But reading this forum and API Doc, I tried following way and that worked for me. If some one also have similar problem, You can try below way as well.

    $http({
          method: 'POST',
          url: "Request URL",           
          params: paramsVal,
          headers: {'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'}
                });
    

    Please check https://docs.angularjs.org/api/ng/service/$http#post for what param config does. {data:'"id":"1"'} – Map of strings or objects which will be turned to URL?data="id:1"

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

    I am using asp.net WCF webservices with angular js and below code worked:

     $http({
            contentType: "application/json; charset=utf-8",//required
            method: "POST",
            url: '../../operation/Service.svc/user_forget',
            dataType: "json",//optional
            data:{ "uid_or_phone": $scope.forgettel, "user_email": $scope.forgetemail },
            async: "isAsync"//optional
    
           }).success( function (response) {
    
             $scope.userforgeterror = response.d;                    
           })
    

    Hope it helps.

    0 讨论(0)
提交回复
热议问题