在下面的代码中,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() {}
});

当前回答

你唯一需要改变的是在创建$http对象时使用属性"params"而不是"data":

$http({
   method: 'POST',
   url: serviceUrl + '/ClientUpdate',
   params: { LangUserId: userId, clientJSON: clients[i] },
})

在上面的例子中,客户端[i]只是JSON对象(没有以任何方式序列化)。如果你使用“params”而不是“data”,angular会使用$httpParamSerializer: https://docs.angularjs.org/api/ng/service/$httpParamSerializer为你序列化对象

其他回答

下面一行需要添加到传递的$http对象中:

headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}

并且传递的数据应该转换为url编码的字符串:

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

你会得到这样的结果:

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

来自:https://groups.google.com/forum/ # !味精naedj1lyo0/4vj_72ezcdsj /角度/ 5

更新

要使用AngularJS V1.4中添加的新服务,请参见

只使用AngularJS服务的url编码变量

var fd = new FormData();
    fd.append('file', file);
    $http.post(uploadUrl, fd, {
        transformRequest: angular.identity,
        headers: {'Content-Type': undefined}
    })
    .success(function(){
    })
    .error(function(){
    });

请付款! https://uncorkedstudios.com/blog/multipartformdata-file-upload-with-angularjs

我目前使用的是我在AngularJS谷歌组中找到的解决方案。

$http
.post('/echo/json/', 'json=' + encodeURIComponent(angular.toJson(data)), {
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
    }
}).success(function(data) {
    $scope.data = data;
});

注意,如果您使用的是PHP,则需要使用类似Symfony 2 HTTP组件的Request::createFromGlobals()来读取该文件,因为$_POST不会自动加载。

我取了一些其他的答案,并使一些东西更干净,把这个.config()调用放在你的angular。模块在你的app.js:

.config(['$httpProvider', function ($httpProvider) {
  // Intercept POST requests, convert to standard form encoding
  $httpProvider.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
  $httpProvider.defaults.transformRequest.unshift(function (data, headersGetter) {
    var key, result = [];

    if (typeof data === "string")
      return data;

    for (key in data) {
      if (data.hasOwnProperty(key))
        result.push(encodeURIComponent(key) + "=" + encodeURIComponent(data[key]));
    }
    return result.join("&");
  });
}]);

你唯一需要改变的是在创建$http对象时使用属性"params"而不是"data":

$http({
   method: 'POST',
   url: serviceUrl + '/ClientUpdate',
   params: { LangUserId: userId, clientJSON: clients[i] },
})

在上面的例子中,客户端[i]只是JSON对象(没有以任何方式序列化)。如果你使用“params”而不是“data”,angular会使用$httpParamSerializer: https://docs.angularjs.org/api/ng/service/$httpParamSerializer为你序列化对象