在下面的代码中,AngularJS $http方法调用URL,并提交xsrf对象作为“Request Payload”(在Chrome调试器网络选项卡中描述)。jQuery $。ajax方法做同样的调用,但提交xsrf作为“表单数据”。

如何让AngularJS将xsrf作为表单数据而不是请求有效载荷提交?

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

当前回答

使用AngularJS的$http服务,并使用它的post方法或配置$http函数。

其他回答

这并不是一个直接的答案,而是一个略有不同的设计方向:

不要将数据作为表单发布,而是作为JSON对象直接映射到服务器端对象,或者使用REST风格的路径变量

现在我知道这两个选项都不适合您的情况,因为您试图传递一个XSRF键。像这样把它映射成一个路径变量是一个糟糕的设计:

http://www.someexample.com/xsrf/{xsrfKey}

因为本质上你会想要传递xsrf密钥到其他路径,/login, /book-appointment等,你不想弄乱你漂亮的URL

有趣的是,将它作为对象字段添加也不合适,因为现在你传递给服务器的每个json对象都必须添加字段

{
  appointmentId : 23,
  name : 'Joe Citizen',
  xsrf : '...'
}

您当然不希望在服务器端类上添加另一个与域对象没有直接语义关联的字段。

在我看来,传递xsrf密钥的最佳方式是通过HTTP报头。许多xsrf保护服务器端web框架库都支持这一点。例如,在Java Spring中,您可以使用X-CSRF-TOKEN头传递它。

Angular出色的将JS对象绑定到UI对象的能力意味着我们可以摆脱一起发布表单的做法,而是发布JSON。JSON可以很容易地反序列化为服务器端对象,并支持复杂的数据结构,如映射、数组、嵌套对象等。

如何在表单有效负载中发布数组?也许是这样的:

shopLocation=downtown&daysOpen=Monday&daysOpen=Tuesday&daysOpen=Wednesday

或:

shopLocation=downtwon&daysOpen=Monday,Tuesday,Wednesday

都是糟糕的设计。

你可以试试下面的溶液

$http({
        method: 'POST',
        url: url-post,
        data: data-post-object-json,
        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
        transformRequest: function(obj) {
            var str = [];
            for (var key in obj) {
                if (obj[key] instanceof Array) {
                    for(var idx in obj[key]){
                        var subObj = obj[key][idx];
                        for(var subKey in subObj){
                            str.push(encodeURIComponent(key) + "[" + idx + "][" + encodeURIComponent(subKey) + "]=" + encodeURIComponent(subObj[subKey]));
                        }
                    }
                }
                else {
                    str.push(encodeURIComponent(key) + "=" + encodeURIComponent(obj[key]));
                }
            }
            return str.join("&");
        }
    }).success(function(response) {
          /* Do something */
        });

在你的应用程序配置-

$httpProvider.defaults.transformRequest = function (data) {
        if (data === undefined)
            return data;
        var clonedData = $.extend(true, {}, data);
        for (var property in clonedData)
            if (property.substr(0, 1) == '$')
                delete clonedData[property];

        return $.param(clonedData);
    };

与您的资源请求-

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

这些答案看起来很疯狂,有时,简单是更好的:

$http.post(loginUrl, "userName=" + encodeURIComponent(email) +
                     "&password=" + encodeURIComponent(password) +
                     "&grant_type=password"
).success(function (data) {
//...

仅仅设置内容类型是不够的,url在发送前对表单数据进行编码。 美元http。帖子(url, jQuery.param(数据)