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

当前回答

作为一种变通方法,你可以简单地让接收POST的代码响应application/json数据。对于PHP,我添加了下面的代码,允许我以表单编码或JSON形式POST到它。

//handles JSON posted arguments and stuffs them into $_POST
//angular's $http makes JSON posts (not normal "form encoded")
$content_type_args = explode(';', $_SERVER['CONTENT_TYPE']); //parse content_type string
if ($content_type_args[0] == 'application/json')
  $_POST = json_decode(file_get_contents('php://input'),true);

//now continue to reference $_POST vars as usual

其他回答

你唯一需要改变的是在创建$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为你序列化对象

AngularJS的做法是正确的,因为它在http-request头中执行了以下内容类型:

Content-Type: application/json

如果你像我一样使用php,甚至使用Symfony2,你可以简单地扩展json标准的服务器兼容性:http://silex.sensiolabs.org/doc/cookbook/json_request_body.html

Symfony2方式(例如在你的DefaultController中):

$request = $this->getRequest();
if (0 === strpos($request->headers->get('Content-Type'), 'application/json')) {
    $data = json_decode($request->getContent(), true);
    $request->request->replace(is_array($data) ? $data : array());
}
var_dump($request->request->all());

好处是,你不需要使用jQuery参数,你可以使用AngularJS的原生方式来做这样的请求。

这就是我所做的我的需要,在那里我需要发送登录数据API作为表单数据和Javascript对象(userData)正在自动转换为URL编码的数据

        var deferred = $q.defer();
        $http({
            method: 'POST',
            url: apiserver + '/authenticate',
            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: userData
        }).success(function (response) {
            //logics
            deferred.resolve(response);
        }).error(function (err, status) {
           deferred.reject(err);
        });

这就是我的用户数据

var userData = {
                grant_type: 'password',
                username: loginData.userName,
                password: loginData.password
            }

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

如果你不想在解决方案中使用jQuery,你可以试试这个。解决方案从这里获取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 () {});