$http.post()不发送数据。

时间:2022-08-22 20:18:04

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 array. If I print message in the console before adding it to the data - it shows the correct content.

有人能告诉我为什么下面的语句没有将post数据发送到指定的url吗?当我打印$_POST时,在服务器上调用url,我得到一个空数组。如果在将消息添加到数据之前在控制台中打印消息,它将显示正确的内容。

$http.post('request-url',  { 'message' : message });

I've also tried it with the data as string (with the same outcome):

我还用数据作为字符串(同样的结果)进行了尝试:

$http.post('request-url',  "message=" + message);

It seem to be working when I use it in the following format:

当我使用以下格式时,它似乎在起作用:

$http({
    method: 'POST',
    url: 'request-url',
    data: "message=" + message,
    headers: {'Content-Type': 'application/x-www-form-urlencoded'}
});

but is there a way of doing it with the $http.post() - and do I always have to include the header in order for it to work? I believe that the above content type is specifying format of the sent data, but can I send it as javascript object?

但是,是否有一种方法可以使用$http.post()来实现它呢?我是否总是必须包含header才能使它生效?我认为上面的内容类型是指定发送数据的格式,但是我可以把它作为javascript对象发送吗?

37 个解决方案

#1


332  

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

我在使用asp.net MVC时遇到了同样的问题,并在这里找到了解决方案。

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.)

对于AngularJS的新成员来说,对于为什么$http服务的简写函数($http.post()等等)不具有可替换性(jQuery.post(),等等),这是非常混乱的。

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

区别在于jQuery和AngularJS如何序列化和传输数据。从根本上说,问题在于您的服务器语言选择无法理解AngularJS的传输…默认情况下,jQuery会使用。

Content-Type: x-www-form-urlencoded

and the familiar foo=bar&baz=moe serialization.

而熟悉的foo=bar&baz=moe序列化。

AngularJS, however, transmits data using

然而,AngularJS使用的是传输数据。

Content-Type: application/json 

and { "foo": "bar", "baz": "moe" }

和{“foo”:“bar”,“baz”:“moe”}

JSON serialization, which unfortunately some Web server languages—notably PHP—do not unserialize natively.

JSON序列化,不幸的是一些Web服务器的语言——尤其是php——并没有在本地进行序列化。

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;
  }];
});

#2


110  

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

上面不是很清楚,但是如果你收到了PHP的请求,你可以使用:

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

$ params = json_decode(file_get_contents(“php:/ /输入”),真的);

To access an array in PHP from an AngularJS POST.

从AngularJS POST访问PHP数组。

#3


74  

You can set the default "Content-Type" like this:

您可以像这样设置默认的“Content-Type”:

$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";

About the data format:

数据格式:

The $http.post and $http.put methods accept any JavaScript object (or a string) value as their data parameter. If data is a JavaScript object it will be, by default, converted to a JSON string.

美元的http。http post和美元。put方法接受任何JavaScript对象(或字符串)值作为其数据参数。如果数据是JavaScript对象,默认情况下它将转换为JSON字符串。

Try to use this variation

试着使用这种变异。

function sendData($scope) {
    $http({
        url: 'request-url',
        method: "POST",
        data: { 'message' : message }
    })
    .then(function(response) {
            // success
    }, 
    function(response) { // optional
            // failed
    });
}

#4


54  

I have had a similar issue, and I wonder if this can be useful as well: https://*.com/a/11443066

我也有过类似的问题,我想知道这是否也有用:https://*.com/a/11443066。

var xsrf = $.param({fkey: "key"});
$http({
    method: 'POST',
    url: url,
    data: xsrf,
    headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})

Regards,

问候,

#5


32  

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

我喜欢使用一个函数来将对象转换为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'}
})

#6


27  

This has finally been addressed in angular 1.4 using $httpParamSerializerJQLike

最后,使用$httpParamSerializerJQLike在角度1.4中解决了这个问题。

See https://github.com/angular/angular.js/issues/6039

参见https://github.com/angular/angular.js/issues/6039

.controller('myCtrl', function($http, $httpParamSerializerJQLike) {
$http({
  method: 'POST',
  url: baseUrl,
  data: $httpParamSerializerJQLike({
    "user":{
      "email":"wahxxx@gmail.com",
      "password":"123456"
    }
  }),
  headers:
    'Content-Type': 'application/x-www-form-urlencoded'
})})

#7


16  

I use jQuery param with AngularJS post requrest. Here is a example ... create AngularJS application module, where myapp is defined with ng-app in your HTML code.

我使用jQuery param与AngularJS post requrest。这里有一个例子……创建AngularJS应用程序模块,myapp在HTML代码中定义为ng-app。

var app = angular.module('myapp', []);

Now let us create a Login controller and POST email and password.

现在,让我们创建一个登录控制器,并发布电子邮件和密码。

app.controller('LoginController', ['$scope', '$http', function ($scope, $http) {
    // default post header
    $http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
    // send login data
    $http({
        method: 'POST',
        url: 'https://example.com/user/login',
        data: $.param({
            email: $scope.email,
            password: $scope.password
        }),
        headers: {'Content-Type': 'application/x-www-form-urlencoded'}
    }).success(function (data, status, headers, config) {
        // handle success things
    }).error(function (data, status, headers, config) {
        // handle error things
    });
}]);

I don't like to exaplain the code, it is simple enough to understand :) Note that param is from jQuery, so you must install both jQuery and AngularJS to make it working. Here is a screenshot.

我不喜欢对代码进行注释,它非常简单易懂:)注意,param来自jQuery,所以必须安装jQuery和AngularJS才能使其工作。这是一个屏幕截图。

$http.post()不发送数据。

Hope this is helpful. Thanks!

希望这是有帮助的。谢谢!

#8


9  

Unlike JQuery and for the sake of pedantry, Angular uses JSON format for POST data transfer from a client to the server (JQuery applies x-www-form-urlencoded presumably, although JQuery and Angular uses JSON for data imput). Therefore there are two parts of problem: in js client part and in your server part. So you need:

不同于JQuery和pedantry,角度使用JSON格式从客户端到服务器的数据传输(JQuery应用了x-www-form-urlencode,尽管JQuery和角度使用JSON用于数据输入)。因此,问题有两部分:在js客户端部分和在您的服务器部分。所以你需要:

  1. put js Angular client part like this:

    将js角客户端部分如下:

    $http({
    method: 'POST',
    url: 'request-url',
    data: {'message': 'Hello world'}
    });
    

AND

  1. write in your server part to receive data from a client (if it is php).

    在服务器端编写从客户端接收数据的部分(如果是php的话)。

            $data               = file_get_contents("php://input");
            $dataJsonDecode     = json_decode($data);
            $message            = $dataJsonDecode->message;
            echo $message;     //'Hello world'
    

Note: $_POST will not work!

注:$_POST不能工作!

The solution works for me fine, hopefully, and for you.

这个解决方案对我来说很好,但愿如此。

#9


8  

I had the same problem with AngularJS and Node.js + Express 4 + Router

我遇到了与AngularJS和Node相同的问题。js + Express 4 +路由器。

Router expects the data from post's request in body. This body was always empty if i followed the example from Angular Docs

路由器期待来自post请求的数据。如果我从角度文档的角度来看,这个物体总是空的。

Notation 1

符号1

$http.post('/someUrl', {msg:'hello word!'})

But if i used it in the data

但如果我在数据中使用它。

Notation 2

符号2

$http({
       withCredentials: false,
       method: 'post',
       url: yourUrl,
       headers: {'Content-Type': 'application/x-www-form-urlencoded'},
       data: postData
 });

Edit 1:

编辑1:

Otherwise node.js router will expect the data in req.body if used notation 1:

否则节点。js路由器在req中会有数据。使用符号1:

req.body.msg

Which also sends the information as JSON payload. This is better in some cases where you have arrays in your json and x-www-form-urlencoded will give some problems.

它还将信息发送为JSON有效负载。在某些情况下,在json和x-www-form-urlencode中有数组会带来一些问题。

it worked. Hope it helps.

它工作。希望它可以帮助。

#10


8  

To send data via Post methode with $http of angularjs you need to change

通过Post methode发送数据,使用$http的angularjs,您需要更改。

data: "message=" + message, with data: $.param({message:message})

数据:“message=”+消息,带有数据:$.param({消息:消息})

#11


7  

To build on @felipe-miosso's answer:

建立在@felipe-miosso的答案上:

  1. Download it as an AngularJS module from here,
  2. 从这里下载一个AngularJS模块,
  3. Install it
  4. 安装它
  5. Add it to your application:

    将其添加到您的应用程序中:

    var app = angular.module('my_app', [ ... , 'httpPostFix']);
    

#12


5  

I don't have the reputation to comment, but in response/addition to Don F's answer:

我没有评论的名声,但是作为回应,我的回答是:

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

$ params = json_decode(file_get_contents(“php:/ /输入”));

A second parameter of true needs to be added to the json_decode function in order to properly return an associative array:

为正确返回关联数组,需要将true的第二个参数添加到json_decode函数中:

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

$ params = json_decode(file_get_contents(“php:/ /输入”),真的);

#13


5  

Angular

  var payload = $.param({ jobId: 2 });

                this.$http({
                    method: 'POST',
                    url: 'web/api/ResourceAction/processfile',
                    data: payload,
                    headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
                });

WebAPI 2

WebAPI 2

public class AcceptJobParams
        {
            public int jobId { get; set; }
        }

        public IHttpActionResult ProcessFile([FromBody]AcceptJobParams thing)
        {
            // do something with fileName parameter

            return Ok();
        }

#14


5  

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";
  }
]);

#15


4  

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.

我也遇到过类似的问题,我做了类似的事情,但没有成功。我的Spring控制器无法读取数据参数。

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.

但是阅读这个论坛和API文档,我尝试了以下方法,这对我很有效。如果有人也有类似的问题,你也可以试试下面的方法。

$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"

请检查https://docs.angularjs.org/api/ng/service/$http#post,以了解param配置的功能。{数据:' id":"1"'} -字符串或对象的映射,将被转到URL?data="id:1"

#16


4  

Add this in your js file:

将这个添加到js文件中:

$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";

and add this to your server file:

并将其添加到您的服务器文件中:

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

That should work.

这应该工作。

#17


4  

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}))

这可能是迟的回答,但我认为最合适的方法是使用相同的代码段角时使用做一个“获得”请求使用美元httpParamSerializer必须注入你的控制器只需执行以下操作,而无需使用Jquery,http.post美元(url,httpParamSerializer美元({参数:val }))

app.controller('ctrl',function($scope,$http,$httpParamSerializer){
    $http.post(url,$httpParamSerializer({param:val,secondParam:secondVal}));
}

#18


3  

I know has accepted answer. But, following might help to future readers, if the answer doesn't suit them for any reason.

我知道已经接受了答案。但是,如果答案不适合他们,那么接下来可能会对未来的读者有所帮助。

Angular doesn't do ajax same as jQuery. While I tried to follow the guide to modify angular $httpprovider , I encountered other problems. E.g. I use codeigniter in which $this->input->is_ajax_request() function always failed (which was written by another programmer and used globally, so cant change) saying this was not real ajax request.

角与jQuery不一样。当我试图按照指南修改角$httpprovider时,我遇到了其他问题。我使用codeigniter,在其中$this->输入->is_ajax_request()函数总是失败(这是由另一个程序员编写的,在全球使用,所以不能更改)说这不是真正的ajax请求。

To solve it, I took help of deferred promise. I tested it in Firefox, and ie9 and it worked.

为了解决这个问题,我求助于延期承诺。我在Firefox和ie9上测试过它。

I have following function defined outside any of the angular code. This function makes regular jquery ajax call and returns deferred/promise (I'm still learning) object.

我有下面的函数定义在任何角码之外。该函数使常规的jquery ajax调用并返回延迟/承诺(我还在学习)对象。

function getjQueryAjax(url, obj){
    return $.ajax({
        type: 'post',
        url: url,
        cache: true,
        data: obj
    });
}

Then I'm calling it angular code using the following code. Please note that we have to update the $scope manually using $scope.$apply() .

然后我用下面的代码调用它的角代码。请注意,我们必须使用$scope手动更新$scope。$apply()。

    var data = {
        media: "video",
        scope: "movies"
    };
    var rPromise = getjQueryAjax("myController/getMeTypes" , data);
    rPromise.success(function(response){
        console.log(response);
        $scope.$apply(function(){
            $scope.testData = JSON.parse(response);
            console.log($scope.testData);
        });
    }).error(function(){
        console.log("AJAX failed!");
    });

This may not be the perfect answer, but it allowed me to use jquery ajax calls with angular and allowed me to update the $scope.

这可能不是完美的答案,但它允许我使用jquery ajax调用,并允许我更新$scope。

#19


3  

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

我使用的asp.net WCF webservices的角js和下面的代码工作:

 $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.

希望它可以帮助。

#20


3  

Didn't find a complete code snippet of how to use $http.post method to send data to the server and why it was not working in this case.

没有找到如何使用$http的完整代码片段。post方法将数据发送到服务器,以及为什么在这种情况下不工作。

Explanations of below code snippet...

以下代码片段的解释…

  1. I am using jQuery $.param function to serialize the JSON data to www post data
  2. 我使用的是jQuery $。param函数将JSON数据序列化为www post数据。
  3. Setting the Content-Type in the config variable that will be passed along with the request of angularJS $http.post that instruct the server that we are sending data in www post format.

    在配置变量中设置内容类型,该变量将随angularJS $http的请求一起传递。post指示服务器我们正在以www post格式发送数据。

  4. Notice the $htttp.post method, where I am sending 1st parameter as url, 2nd parameter as data (serialized) and 3rd parameter as config.

    注意到htttp美元。post方法,我将第一个参数作为url发送,第二个参数作为数据(序列化)和第三个参数作为配置。

Remaining code is self understood.

剩下的代码是自我理解的。

$scope.SendData = function () {
           // use $.param jQuery function to serialize data from JSON 
            var data = $.param({
                fName: $scope.firstName,
                lName: $scope.lastName
            });

            var config = {
                headers : {
                    'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
                }
            }

            $http.post('/ServerRequest/PostDataResponse', data, config)
            .success(function (data, status, headers, config) {
                $scope.PostDataResponse = data;
            })
            .error(function (data, status, header, config) {
                $scope.ResponseDetails = "Data: " + data +
                    "<hr />status: " + status +
                    "<hr />headers: " + header +
                    "<hr />config: " + config;
            });
        };

Look at the code example of $http.post method here.

查看$http的代码示例。post方法。

#21


3  

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

如果使用角>= 1.4,这是使用角的序列化器提供的最干净的解决方案:

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.

它将正确地将数据序列化为param1=value1&param2=value2,并将其发送到/requesturl与应用程序/x-www-form-urlencode;charset=utf-8 Content-Type头,因为它通常被期望在端点上的POST请求。

TL;DR

博士TL;

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.

在我的研究中,我发现这个问题的答案有很多不同的口味;有些是非常复杂的,依赖于自定义函数,有些依赖于jQuery,还有一些是不完整的,建议您只需要设置标题。

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.

如果你只设置content - type头,终点将POST数据,但它不会在标准格式,因为除非你提供一个字符串数据,或者手工序列化数据对象,默认情况下它都将被序列化为JSON和可能错误地解读端点。

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.

这可能会导致意想不到的解析,例如ASP。NET把它当作一个空参数名,用{“param1”:“value1”,“param2”:“value2”}为值;或者Fiddler以另一种方式解释它,用{“param1”:“value1”,“param2”:“value2”}作为参数名,null作为值。

#22


3  

Similar to the OP's suggested working format & Denison's answer, except using $http.post instead of just $http and is still dependent on jQuery.

与OP的建议的工作格式和Denison的答案类似,除了使用$http。post而不是$http,仍然依赖于jQuery。

The good thing about using jQuery here is that complex objects get passed properly; against manually converting into URL parameters which may garble the data.

使用jQuery的好处是,复杂的对象可以正确地传递;反对手工转换为URL参数,这可能会篡改数据。

$http.post( 'request-url', jQuery.param( { 'message': message } ), {
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
});

#23


3  

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" :-)

您需要使用JSON。对包含JSON对象的每个param进行stringify,然后用“$”构建数据对象。param”:-)

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

NB:我的“objJSON”是一个JSON对象,包含数组、整数、字符串和html内容。他的总尺寸是>,3500个字符。

#24


2  

When I had this problem the parameter I was posting turned out to be an array of objects instead of a simple object.

当我有这个问题时,我所发布的参数被证明是一个对象数组,而不是一个简单的对象。

#25


2  

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

我在快递方面遇到了同样的问题。要解决这个问题,必须在发送http请求之前使用bodyparser来解析json对象。

app.use(bodyParser.json());

#26


2  

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...

刚刚从角1.2到1.3的更新,在代码中发现了一个问题。转换资源将导致一个不循环,因为(我认为)$promise再次持有相同的对象。也许它会帮助某人……

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) {
[...]

#27


2  

I've been using the accepted answer's code (Felipe's code) for a while and it's been working great (thanks, Felipe!).

我已经使用了一段时间的被接受的答案代码(斐利贝的代码),而且它运行得很好(谢谢,Felipe!)

However, recently I discovered that it has issues with empty objects or arrays. For example, when submitting this object:

但是,最近我发现它存在空对象或数组的问题。例如,提交该对象时:

{
    A: 1,
    B: {
        a: [ ],
    },
    C: [ ],
    D: "2"
}

PHP doesn't seem to see B and C at all. It gets this:

PHP似乎没有看到B和C。就这样:

[
    "A" => "1",
    "B" => "2"
]

A look at the actual request in Chrome shows this:

看一下Chrome的实际需求就会发现:

A: 1
:
D: 2

I wrote an alternative code snippet. It seems to work well with my use-cases but I haven't tested it extensively so use with caution.

我编写了另一个代码片段。它似乎可以很好地处理我的用例,但我还没有对它进行广泛的测试,所以要谨慎使用。

I used TypeScript because I like strong typing but it would be easy to convert to pure JS:

我使用打字稿,因为我喜欢强类型,但容易转换成纯粹的JS:

angular.module("MyModule").config([ "$httpProvider", function($httpProvider: ng.IHttpProvider) {
    // Use x-www-form-urlencoded Content-Type
    $httpProvider.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded;charset=utf-8";

    function phpize(obj: Object | any[], depth: number = 1): string[] {
        var arr: string[] = [ ];
        angular.forEach(obj, (value: any, key: string) => {
            if (angular.isObject(value) || angular.isArray(value)) {
                var arrInner: string[] = phpize(value, depth + 1);
                var tmpKey: string;
                var encodedKey = encodeURIComponent(key);
                if (depth == 1) tmpKey = encodedKey;
                else tmpKey = `[${encodedKey}]`;
                if (arrInner.length == 0) {
                    arr.push(`${tmpKey}=`);
                }
                else {
                    arr = arr.concat(arrInner.map(inner => `${tmpKey}${inner}`));
                }
            }
            else {
                var encodedKey = encodeURIComponent(key);
                var encodedValue;
                if (angular.isUndefined(value) || value === null) encodedValue = "";
                else encodedValue = encodeURIComponent(value);

                if (depth == 1) {
                    arr.push(`${encodedKey}=${encodedValue}`);
                }
                else {
                    arr.push(`[${encodedKey}]=${encodedValue}`);
                }
            }
        });
        return arr;
    }

    // Override $http service's default transformRequest
    (<any>$httpProvider.defaults).transformRequest = [ function(data: any) {
        if (!angular.isObject(data) || data.toString() == "[object File]") return data;
        return phpize(data).join("&");
    } ];
} ]);

It's less efficient than Felipe's code but I don't think it matters much since it should be immediate compared to the overall overhead of the HTTP request itself.

它比Felipe的代码效率低,但是我不认为它很重要,因为它应该与HTTP请求本身的总体开销比较起来。

Now PHP shows:

现在PHP显示:

[
    "A" => "1",
    "B" => [
        "a" => ""
    ],
    "C" => "",
    "D" => "2"
]

As far as I know it's not possible to get PHP to recognize that B.a and C are empty arrays, but at least the keys appear, which is important when there's code that relies on the a certain structure even when its essentially empty inside.

就我所知,让PHP识别B是不可能的。a和C是空的数组,但至少键出现了,这对于依赖于某个结构的代码是很重要的,即使它本质上是空的。

Also note that it converts undefineds and nulls to empty strings.

还要注意,它将undefineds和nulls转换为空字符串。

#28


2  

If your using PHP this is a easy way to access an array in PHP from an AngularJS POST.

如果您使用PHP,这是一种从AngularJS POST访问PHP数组的简单方法。

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

#29


2  

Just put the data you want to send as second parameter:

只需将想发送的数据作为第二个参数发送:

$http.post('request-url',  message);

Another form which also works is:

另一种形式是:

$http.post('request-url',  { params: { paramName: value } });

Make sure that paramName exactly matches the name of the parameter of the function you are calling.

确保paramName完全匹配您调用的函数的参数的名称。

Source: AngularJS post shortcut method

来源:AngularJS邮政快捷方式。

#30


1  

I solved this by below codes:

我用下面的代码解决了这个问题:

Client Side (Js):

客户端(Js):

     $http({
                url: me.serverPath,
                method: 'POST',
                data: data,
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            }).
                success(function (serverData) {
                    console.log("ServerData:", serverData);
    ......

notice that data is an object.

注意,数据是一个对象。

On the server (ASP.NET MVC):

在服务器上(ASP。NET MVC):

[AllowCrossSiteJson]
        public string Api()
        {
            var data = JsonConvert.DeserializeObject<AgentRequest>(Request.Form[0]);
            if (data == null) return "Null Request";
            var bl = Page.Bl = new Core(this);

            return data.methodName;
        }

and 'AllowCrossSiteJsonAttribute' is needed for cross domain requests:

跨域请求需要“AllowCrossSiteJsonAttribute”:

public class AllowCrossSiteJsonAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Origin", "*");
            base.OnActionExecuting(filterContext);
        }
    }

Hope this was useful.

希望这是有用的。

#1


332  

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

我在使用asp.net MVC时遇到了同样的问题,并在这里找到了解决方案。

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.)

对于AngularJS的新成员来说,对于为什么$http服务的简写函数($http.post()等等)不具有可替换性(jQuery.post(),等等),这是非常混乱的。

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

区别在于jQuery和AngularJS如何序列化和传输数据。从根本上说,问题在于您的服务器语言选择无法理解AngularJS的传输…默认情况下,jQuery会使用。

Content-Type: x-www-form-urlencoded

and the familiar foo=bar&baz=moe serialization.

而熟悉的foo=bar&baz=moe序列化。

AngularJS, however, transmits data using

然而,AngularJS使用的是传输数据。

Content-Type: application/json 

and { "foo": "bar", "baz": "moe" }

和{“foo”:“bar”,“baz”:“moe”}

JSON serialization, which unfortunately some Web server languages—notably PHP—do not unserialize natively.

JSON序列化,不幸的是一些Web服务器的语言——尤其是php——并没有在本地进行序列化。

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;
  }];
});

#2


110  

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

上面不是很清楚,但是如果你收到了PHP的请求,你可以使用:

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

$ params = json_decode(file_get_contents(“php:/ /输入”),真的);

To access an array in PHP from an AngularJS POST.

从AngularJS POST访问PHP数组。

#3


74  

You can set the default "Content-Type" like this:

您可以像这样设置默认的“Content-Type”:

$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";

About the data format:

数据格式:

The $http.post and $http.put methods accept any JavaScript object (or a string) value as their data parameter. If data is a JavaScript object it will be, by default, converted to a JSON string.

美元的http。http post和美元。put方法接受任何JavaScript对象(或字符串)值作为其数据参数。如果数据是JavaScript对象,默认情况下它将转换为JSON字符串。

Try to use this variation

试着使用这种变异。

function sendData($scope) {
    $http({
        url: 'request-url',
        method: "POST",
        data: { 'message' : message }
    })
    .then(function(response) {
            // success
    }, 
    function(response) { // optional
            // failed
    });
}

#4


54  

I have had a similar issue, and I wonder if this can be useful as well: https://*.com/a/11443066

我也有过类似的问题,我想知道这是否也有用:https://*.com/a/11443066。

var xsrf = $.param({fkey: "key"});
$http({
    method: 'POST',
    url: url,
    data: xsrf,
    headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})

Regards,

问候,

#5


32  

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

我喜欢使用一个函数来将对象转换为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'}
})

#6


27  

This has finally been addressed in angular 1.4 using $httpParamSerializerJQLike

最后,使用$httpParamSerializerJQLike在角度1.4中解决了这个问题。

See https://github.com/angular/angular.js/issues/6039

参见https://github.com/angular/angular.js/issues/6039

.controller('myCtrl', function($http, $httpParamSerializerJQLike) {
$http({
  method: 'POST',
  url: baseUrl,
  data: $httpParamSerializerJQLike({
    "user":{
      "email":"wahxxx@gmail.com",
      "password":"123456"
    }
  }),
  headers:
    'Content-Type': 'application/x-www-form-urlencoded'
})})

#7


16  

I use jQuery param with AngularJS post requrest. Here is a example ... create AngularJS application module, where myapp is defined with ng-app in your HTML code.

我使用jQuery param与AngularJS post requrest。这里有一个例子……创建AngularJS应用程序模块,myapp在HTML代码中定义为ng-app。

var app = angular.module('myapp', []);

Now let us create a Login controller and POST email and password.

现在,让我们创建一个登录控制器,并发布电子邮件和密码。

app.controller('LoginController', ['$scope', '$http', function ($scope, $http) {
    // default post header
    $http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
    // send login data
    $http({
        method: 'POST',
        url: 'https://example.com/user/login',
        data: $.param({
            email: $scope.email,
            password: $scope.password
        }),
        headers: {'Content-Type': 'application/x-www-form-urlencoded'}
    }).success(function (data, status, headers, config) {
        // handle success things
    }).error(function (data, status, headers, config) {
        // handle error things
    });
}]);

I don't like to exaplain the code, it is simple enough to understand :) Note that param is from jQuery, so you must install both jQuery and AngularJS to make it working. Here is a screenshot.

我不喜欢对代码进行注释,它非常简单易懂:)注意,param来自jQuery,所以必须安装jQuery和AngularJS才能使其工作。这是一个屏幕截图。

$http.post()不发送数据。

Hope this is helpful. Thanks!

希望这是有帮助的。谢谢!

#8


9  

Unlike JQuery and for the sake of pedantry, Angular uses JSON format for POST data transfer from a client to the server (JQuery applies x-www-form-urlencoded presumably, although JQuery and Angular uses JSON for data imput). Therefore there are two parts of problem: in js client part and in your server part. So you need:

不同于JQuery和pedantry,角度使用JSON格式从客户端到服务器的数据传输(JQuery应用了x-www-form-urlencode,尽管JQuery和角度使用JSON用于数据输入)。因此,问题有两部分:在js客户端部分和在您的服务器部分。所以你需要:

  1. put js Angular client part like this:

    将js角客户端部分如下:

    $http({
    method: 'POST',
    url: 'request-url',
    data: {'message': 'Hello world'}
    });
    

AND

  1. write in your server part to receive data from a client (if it is php).

    在服务器端编写从客户端接收数据的部分(如果是php的话)。

            $data               = file_get_contents("php://input");
            $dataJsonDecode     = json_decode($data);
            $message            = $dataJsonDecode->message;
            echo $message;     //'Hello world'
    

Note: $_POST will not work!

注:$_POST不能工作!

The solution works for me fine, hopefully, and for you.

这个解决方案对我来说很好,但愿如此。

#9


8  

I had the same problem with AngularJS and Node.js + Express 4 + Router

我遇到了与AngularJS和Node相同的问题。js + Express 4 +路由器。

Router expects the data from post's request in body. This body was always empty if i followed the example from Angular Docs

路由器期待来自post请求的数据。如果我从角度文档的角度来看,这个物体总是空的。

Notation 1

符号1

$http.post('/someUrl', {msg:'hello word!'})

But if i used it in the data

但如果我在数据中使用它。

Notation 2

符号2

$http({
       withCredentials: false,
       method: 'post',
       url: yourUrl,
       headers: {'Content-Type': 'application/x-www-form-urlencoded'},
       data: postData
 });

Edit 1:

编辑1:

Otherwise node.js router will expect the data in req.body if used notation 1:

否则节点。js路由器在req中会有数据。使用符号1:

req.body.msg

Which also sends the information as JSON payload. This is better in some cases where you have arrays in your json and x-www-form-urlencoded will give some problems.

它还将信息发送为JSON有效负载。在某些情况下,在json和x-www-form-urlencode中有数组会带来一些问题。

it worked. Hope it helps.

它工作。希望它可以帮助。

#10


8  

To send data via Post methode with $http of angularjs you need to change

通过Post methode发送数据,使用$http的angularjs,您需要更改。

data: "message=" + message, with data: $.param({message:message})

数据:“message=”+消息,带有数据:$.param({消息:消息})

#11


7  

To build on @felipe-miosso's answer:

建立在@felipe-miosso的答案上:

  1. Download it as an AngularJS module from here,
  2. 从这里下载一个AngularJS模块,
  3. Install it
  4. 安装它
  5. Add it to your application:

    将其添加到您的应用程序中:

    var app = angular.module('my_app', [ ... , 'httpPostFix']);
    

#12


5  

I don't have the reputation to comment, but in response/addition to Don F's answer:

我没有评论的名声,但是作为回应,我的回答是:

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

$ params = json_decode(file_get_contents(“php:/ /输入”));

A second parameter of true needs to be added to the json_decode function in order to properly return an associative array:

为正确返回关联数组,需要将true的第二个参数添加到json_decode函数中:

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

$ params = json_decode(file_get_contents(“php:/ /输入”),真的);

#13


5  

Angular

  var payload = $.param({ jobId: 2 });

                this.$http({
                    method: 'POST',
                    url: 'web/api/ResourceAction/processfile',
                    data: payload,
                    headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
                });

WebAPI 2

WebAPI 2

public class AcceptJobParams
        {
            public int jobId { get; set; }
        }

        public IHttpActionResult ProcessFile([FromBody]AcceptJobParams thing)
        {
            // do something with fileName parameter

            return Ok();
        }

#14


5  

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";
  }
]);

#15


4  

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.

我也遇到过类似的问题,我做了类似的事情,但没有成功。我的Spring控制器无法读取数据参数。

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.

但是阅读这个论坛和API文档,我尝试了以下方法,这对我很有效。如果有人也有类似的问题,你也可以试试下面的方法。

$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"

请检查https://docs.angularjs.org/api/ng/service/$http#post,以了解param配置的功能。{数据:' id":"1"'} -字符串或对象的映射,将被转到URL?data="id:1"

#16


4  

Add this in your js file:

将这个添加到js文件中:

$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";

and add this to your server file:

并将其添加到您的服务器文件中:

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

That should work.

这应该工作。

#17


4  

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}))

这可能是迟的回答,但我认为最合适的方法是使用相同的代码段角时使用做一个“获得”请求使用美元httpParamSerializer必须注入你的控制器只需执行以下操作,而无需使用Jquery,http.post美元(url,httpParamSerializer美元({参数:val }))

app.controller('ctrl',function($scope,$http,$httpParamSerializer){
    $http.post(url,$httpParamSerializer({param:val,secondParam:secondVal}));
}

#18


3  

I know has accepted answer. But, following might help to future readers, if the answer doesn't suit them for any reason.

我知道已经接受了答案。但是,如果答案不适合他们,那么接下来可能会对未来的读者有所帮助。

Angular doesn't do ajax same as jQuery. While I tried to follow the guide to modify angular $httpprovider , I encountered other problems. E.g. I use codeigniter in which $this->input->is_ajax_request() function always failed (which was written by another programmer and used globally, so cant change) saying this was not real ajax request.

角与jQuery不一样。当我试图按照指南修改角$httpprovider时,我遇到了其他问题。我使用codeigniter,在其中$this->输入->is_ajax_request()函数总是失败(这是由另一个程序员编写的,在全球使用,所以不能更改)说这不是真正的ajax请求。

To solve it, I took help of deferred promise. I tested it in Firefox, and ie9 and it worked.

为了解决这个问题,我求助于延期承诺。我在Firefox和ie9上测试过它。

I have following function defined outside any of the angular code. This function makes regular jquery ajax call and returns deferred/promise (I'm still learning) object.

我有下面的函数定义在任何角码之外。该函数使常规的jquery ajax调用并返回延迟/承诺(我还在学习)对象。

function getjQueryAjax(url, obj){
    return $.ajax({
        type: 'post',
        url: url,
        cache: true,
        data: obj
    });
}

Then I'm calling it angular code using the following code. Please note that we have to update the $scope manually using $scope.$apply() .

然后我用下面的代码调用它的角代码。请注意,我们必须使用$scope手动更新$scope。$apply()。

    var data = {
        media: "video",
        scope: "movies"
    };
    var rPromise = getjQueryAjax("myController/getMeTypes" , data);
    rPromise.success(function(response){
        console.log(response);
        $scope.$apply(function(){
            $scope.testData = JSON.parse(response);
            console.log($scope.testData);
        });
    }).error(function(){
        console.log("AJAX failed!");
    });

This may not be the perfect answer, but it allowed me to use jquery ajax calls with angular and allowed me to update the $scope.

这可能不是完美的答案,但它允许我使用jquery ajax调用,并允许我更新$scope。

#19


3  

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

我使用的asp.net WCF webservices的角js和下面的代码工作:

 $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.

希望它可以帮助。

#20


3  

Didn't find a complete code snippet of how to use $http.post method to send data to the server and why it was not working in this case.

没有找到如何使用$http的完整代码片段。post方法将数据发送到服务器,以及为什么在这种情况下不工作。

Explanations of below code snippet...

以下代码片段的解释…

  1. I am using jQuery $.param function to serialize the JSON data to www post data
  2. 我使用的是jQuery $。param函数将JSON数据序列化为www post数据。
  3. Setting the Content-Type in the config variable that will be passed along with the request of angularJS $http.post that instruct the server that we are sending data in www post format.

    在配置变量中设置内容类型,该变量将随angularJS $http的请求一起传递。post指示服务器我们正在以www post格式发送数据。

  4. Notice the $htttp.post method, where I am sending 1st parameter as url, 2nd parameter as data (serialized) and 3rd parameter as config.

    注意到htttp美元。post方法,我将第一个参数作为url发送,第二个参数作为数据(序列化)和第三个参数作为配置。

Remaining code is self understood.

剩下的代码是自我理解的。

$scope.SendData = function () {
           // use $.param jQuery function to serialize data from JSON 
            var data = $.param({
                fName: $scope.firstName,
                lName: $scope.lastName
            });

            var config = {
                headers : {
                    'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
                }
            }

            $http.post('/ServerRequest/PostDataResponse', data, config)
            .success(function (data, status, headers, config) {
                $scope.PostDataResponse = data;
            })
            .error(function (data, status, header, config) {
                $scope.ResponseDetails = "Data: " + data +
                    "<hr />status: " + status +
                    "<hr />headers: " + header +
                    "<hr />config: " + config;
            });
        };

Look at the code example of $http.post method here.

查看$http的代码示例。post方法。

#21


3  

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

如果使用角>= 1.4,这是使用角的序列化器提供的最干净的解决方案:

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.

它将正确地将数据序列化为param1=value1&param2=value2,并将其发送到/requesturl与应用程序/x-www-form-urlencode;charset=utf-8 Content-Type头,因为它通常被期望在端点上的POST请求。

TL;DR

博士TL;

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.

在我的研究中,我发现这个问题的答案有很多不同的口味;有些是非常复杂的,依赖于自定义函数,有些依赖于jQuery,还有一些是不完整的,建议您只需要设置标题。

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.

如果你只设置content - type头,终点将POST数据,但它不会在标准格式,因为除非你提供一个字符串数据,或者手工序列化数据对象,默认情况下它都将被序列化为JSON和可能错误地解读端点。

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.

这可能会导致意想不到的解析,例如ASP。NET把它当作一个空参数名,用{“param1”:“value1”,“param2”:“value2”}为值;或者Fiddler以另一种方式解释它,用{“param1”:“value1”,“param2”:“value2”}作为参数名,null作为值。

#22


3  

Similar to the OP's suggested working format & Denison's answer, except using $http.post instead of just $http and is still dependent on jQuery.

与OP的建议的工作格式和Denison的答案类似,除了使用$http。post而不是$http,仍然依赖于jQuery。

The good thing about using jQuery here is that complex objects get passed properly; against manually converting into URL parameters which may garble the data.

使用jQuery的好处是,复杂的对象可以正确地传递;反对手工转换为URL参数,这可能会篡改数据。

$http.post( 'request-url', jQuery.param( { 'message': message } ), {
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
});

#23


3  

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" :-)

您需要使用JSON。对包含JSON对象的每个param进行stringify,然后用“$”构建数据对象。param”:-)

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

NB:我的“objJSON”是一个JSON对象,包含数组、整数、字符串和html内容。他的总尺寸是>,3500个字符。

#24


2  

When I had this problem the parameter I was posting turned out to be an array of objects instead of a simple object.

当我有这个问题时,我所发布的参数被证明是一个对象数组,而不是一个简单的对象。

#25


2  

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

我在快递方面遇到了同样的问题。要解决这个问题,必须在发送http请求之前使用bodyparser来解析json对象。

app.use(bodyParser.json());

#26


2  

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...

刚刚从角1.2到1.3的更新,在代码中发现了一个问题。转换资源将导致一个不循环,因为(我认为)$promise再次持有相同的对象。也许它会帮助某人……

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) {
[...]

#27


2  

I've been using the accepted answer's code (Felipe's code) for a while and it's been working great (thanks, Felipe!).

我已经使用了一段时间的被接受的答案代码(斐利贝的代码),而且它运行得很好(谢谢,Felipe!)

However, recently I discovered that it has issues with empty objects or arrays. For example, when submitting this object:

但是,最近我发现它存在空对象或数组的问题。例如,提交该对象时:

{
    A: 1,
    B: {
        a: [ ],
    },
    C: [ ],
    D: "2"
}

PHP doesn't seem to see B and C at all. It gets this:

PHP似乎没有看到B和C。就这样:

[
    "A" => "1",
    "B" => "2"
]

A look at the actual request in Chrome shows this:

看一下Chrome的实际需求就会发现:

A: 1
:
D: 2

I wrote an alternative code snippet. It seems to work well with my use-cases but I haven't tested it extensively so use with caution.

我编写了另一个代码片段。它似乎可以很好地处理我的用例,但我还没有对它进行广泛的测试,所以要谨慎使用。

I used TypeScript because I like strong typing but it would be easy to convert to pure JS:

我使用打字稿,因为我喜欢强类型,但容易转换成纯粹的JS:

angular.module("MyModule").config([ "$httpProvider", function($httpProvider: ng.IHttpProvider) {
    // Use x-www-form-urlencoded Content-Type
    $httpProvider.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded;charset=utf-8";

    function phpize(obj: Object | any[], depth: number = 1): string[] {
        var arr: string[] = [ ];
        angular.forEach(obj, (value: any, key: string) => {
            if (angular.isObject(value) || angular.isArray(value)) {
                var arrInner: string[] = phpize(value, depth + 1);
                var tmpKey: string;
                var encodedKey = encodeURIComponent(key);
                if (depth == 1) tmpKey = encodedKey;
                else tmpKey = `[${encodedKey}]`;
                if (arrInner.length == 0) {
                    arr.push(`${tmpKey}=`);
                }
                else {
                    arr = arr.concat(arrInner.map(inner => `${tmpKey}${inner}`));
                }
            }
            else {
                var encodedKey = encodeURIComponent(key);
                var encodedValue;
                if (angular.isUndefined(value) || value === null) encodedValue = "";
                else encodedValue = encodeURIComponent(value);

                if (depth == 1) {
                    arr.push(`${encodedKey}=${encodedValue}`);
                }
                else {
                    arr.push(`[${encodedKey}]=${encodedValue}`);
                }
            }
        });
        return arr;
    }

    // Override $http service's default transformRequest
    (<any>$httpProvider.defaults).transformRequest = [ function(data: any) {
        if (!angular.isObject(data) || data.toString() == "[object File]") return data;
        return phpize(data).join("&");
    } ];
} ]);

It's less efficient than Felipe's code but I don't think it matters much since it should be immediate compared to the overall overhead of the HTTP request itself.

它比Felipe的代码效率低,但是我不认为它很重要,因为它应该与HTTP请求本身的总体开销比较起来。

Now PHP shows:

现在PHP显示:

[
    "A" => "1",
    "B" => [
        "a" => ""
    ],
    "C" => "",
    "D" => "2"
]

As far as I know it's not possible to get PHP to recognize that B.a and C are empty arrays, but at least the keys appear, which is important when there's code that relies on the a certain structure even when its essentially empty inside.

就我所知,让PHP识别B是不可能的。a和C是空的数组,但至少键出现了,这对于依赖于某个结构的代码是很重要的,即使它本质上是空的。

Also note that it converts undefineds and nulls to empty strings.

还要注意,它将undefineds和nulls转换为空字符串。

#28


2  

If your using PHP this is a easy way to access an array in PHP from an AngularJS POST.

如果您使用PHP,这是一种从AngularJS POST访问PHP数组的简单方法。

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

#29


2  

Just put the data you want to send as second parameter:

只需将想发送的数据作为第二个参数发送:

$http.post('request-url',  message);

Another form which also works is:

另一种形式是:

$http.post('request-url',  { params: { paramName: value } });

Make sure that paramName exactly matches the name of the parameter of the function you are calling.

确保paramName完全匹配您调用的函数的参数的名称。

Source: AngularJS post shortcut method

来源:AngularJS邮政快捷方式。

#30


1  

I solved this by below codes:

我用下面的代码解决了这个问题:

Client Side (Js):

客户端(Js):

     $http({
                url: me.serverPath,
                method: 'POST',
                data: data,
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            }).
                success(function (serverData) {
                    console.log("ServerData:", serverData);
    ......

notice that data is an object.

注意,数据是一个对象。

On the server (ASP.NET MVC):

在服务器上(ASP。NET MVC):

[AllowCrossSiteJson]
        public string Api()
        {
            var data = JsonConvert.DeserializeObject<AgentRequest>(Request.Form[0]);
            if (data == null) return "Null Request";
            var bl = Page.Bl = new Core(this);

            return data.methodName;
        }

and 'AllowCrossSiteJsonAttribute' is needed for cross domain requests:

跨域请求需要“AllowCrossSiteJsonAttribute”:

public class AllowCrossSiteJsonAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Origin", "*");
            base.OnActionExecuting(filterContext);
        }
    }

Hope this was useful.

希望这是有用的。