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() {}
});

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

From: https://groups.google.com/forum/#!msg/angular/5nAedJ1LyO0/4Vj_72EZcDsJ


If you do not want to use jQuery in the solution you could try this. Solution nabbed from here https://stackoverflow.com/a/1714899/1784301

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

The continued confusion surrounding this issue inspired me to write a blog post about it. The solution I propose in this post is better than your current top rated solution because it does not restrict you to parametrizing your data object for $http service calls; ie with my solution you can simply continue to pass actual data objects to $http.post(), etc. and still achieve the desired result.

Also, the top rated answer relies on the inclusion of full jQuery in the page for the $.param() function, whereas my solution is jQuery agnostic, pure AngularJS ready.

http://victorblog.com/2012/12/20/make-angularjs-http-service-behave-like-jquery-ajax/

Hope this helps.

链接地址: http://www.djcxy.com/p/41080.html

上一篇: 如何使用Composer安装Composer?

下一篇: 如何将数据发布为表单数据而不是请求有效内容?