AngularJs $http.post() does not send data

2018-12-31 05:29发布

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.

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

30条回答
心情的温度
2楼-- · 2018-12-31 05:57

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());
查看更多
姐姐魅力值爆表
3楼-- · 2018-12-31 05:57

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.

查看更多
宁负流年不负卿
4楼-- · 2018-12-31 05:57

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.

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.

$http.post( 'request-url', jQuery.param( { 'message': message } ), {
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
});
查看更多
浪荡孟婆
5楼-- · 2018-12-31 05:58

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.

Explanations of below code snippet...

  1. I am using jQuery $.param function to serialize the JSON data to www post data
  2. 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.

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

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.

查看更多
旧时光的记忆
6楼-- · 2018-12-31 05:59

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"

查看更多
旧人旧事旧时光
7楼-- · 2018-12-31 05:59

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

查看更多
登录 后发表回答