0

I post data to node application from a cordova app using angular $http.

I tried several 'content-type', and only 'application/x-www-form-urlencoded' can be sent to the node server successfully, so my code is like:

$http({
        url: CONSTANTS.login_url,
        method: "POST",
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        },
        data: {"foo": "bar"},
      })

But in the node application, the data I got from req.body is:

{"{"foo":"bar"}":""}

The key of the body is a String.

But my excepted result should be an Object like:

{
  "foo": "bar",
}

There is a similar question in SO, the reason is that he uses 'JSON.stringify' in the frontend. But I don't use stringify why I can't get the excepted data?

Glen
  • 13
  • 3
  • Possible duplicate of [How do I POST urlencoded form data with $http in AngularJS?](http://stackoverflow.com/questions/24710503/how-do-i-post-urlencoded-form-data-with-http-in-angularjs) – str Sep 15 '16 at 08:18

1 Answers1

0

Add a trnsformRequest function to transform the data to match the content-type

$http({
    url: CONSTANTS.login_url,
    method: 'POST',
    url: url,
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    data: {"foo": "bar"},
    transformRequest: function(obj) {
        var str = [];
        for(var p in obj)
        str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
        return str.join("&");
    }
}).success(function () {});

answer borrowed from here

hope this helps.

Community
  • 1
  • 1
shakib
  • 5,449
  • 2
  • 30
  • 39
  • 1
    @shakib It is better to mark the question as duplicate than to copy the answer from elsewhere. – str Sep 15 '16 at 08:36