2017  Kodetalk | Feedback | Privacy Policy | Terms | About
userimage

How can I post data as form data instead of a request payload?


In the code below, the AngularJS $http method calls the URL, and submits the xsrf object as a "Request Payload" (as described in the Chrome debugger network tab). The jQuery $.ajax method does the same call, but submits xsrf as "Form Data".

How can I make AngularJS submit xsrf as form data instead of a request payload?

var url = "http://somewhere.com/";
var xsrf = {fkey: "xsrf key"};

$http({
    method: "POST",
    url: url,
    data: xsrf
}).success(function () {});

$.ajax({
    type: "POST",
    url: url,
    data: xsrf,
    dataType: "json",
    success: function() {}
});


userimage

The following line needs to be added to the $http object that is passed:

headers: {'Content-Type': 'application/x-www-form-urlencoded'}

And the data passed should be converted to a URL-encoded string:

> $.param({fkey: "key"})
'fkey=key'

So you have something like:

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

Answer is