有人能告诉我为什么下面的语句没有将post数据发送到指定的url吗?url被调用,但在服务器上,当我打印$_POST -我得到一个空数组。如果我在控制台中打印消息,然后将其添加到数据-它显示了正确的内容。

$http.post('request-url',  { 'message' : message });

我也尝试过将数据作为字符串(具有相同的结果):

$http.post('request-url',  "message=" + message);

当我以以下格式使用它时,它似乎正在工作:

$http({
    method: 'POST',
    url: 'request-url',
    data: "message=" + message,
    headers: {'Content-Type': 'application/x-www-form-urlencoded'}
});

但是是否有一种方法可以用$http.post() -我总是必须包括头以便它工作吗?我相信上面的内容类型是指定发送数据的格式,但我可以把它作为javascript对象发送吗?


当前回答

在你的js文件中添加这个:

$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";

并添加到您的服务器文件:

$params = json_decode(file_get_contents('php://input'), true);

这应该有用。

其他回答

我在使用asp.net MVC时遇到了同样的问题,在这里找到了解决方案

刚接触AngularJS的人有很多困惑,为什么 $http服务简写函数($http.post()等)不会出现 可切换与jQuery的等价物(jQuery.post()等) 不同之处在于jQuery和AngularJS如何序列化和传输数据。从根本上说,问题在于你所选择的服务器语言无法理解AngularJS的传输…jQuery默认使用

Content-Type: x-www-form-urlencoded

以及熟悉的foo=bar&baz=moe序列化。

AngularJS使用

Content-Type: application/json 

{"foo": "bar", "baz": "moe"}

JSON序列化,不幸的是一些Web服务器语言—特别是 php—不要本地反序列化。

效果非常好。

CODE

// Your app's root module...
angular.module('MyModule', [], function($httpProvider) {
  // Use x-www-form-urlencoded Content-Type
  $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
 
  /**
   * The workhorse; converts an object to x-www-form-urlencoded serialization.
   * @param {Object} obj
   * @return {String}
   */ 
  var param = function(obj) {
    var query = '', name, value, fullSubName, subName, subValue, innerObj, i;
      
    for(name in obj) {
      value = obj[name];
        
      if(value instanceof Array) {
        for(i=0; i<value.length; ++i) {
          subValue = value[i];
          fullSubName = name + '[' + i + ']';
          innerObj = {};
          innerObj[fullSubName] = subValue;
          query += param(innerObj) + '&';
        }
      }
      else if(value instanceof Object) {
        for(subName in value) {
          subValue = value[subName];
          fullSubName = name + '[' + subName + ']';
          innerObj = {};
          innerObj[fullSubName] = subValue;
          query += param(innerObj) + '&';
        }
      }
      else if(value !== undefined && value !== null)
        query += encodeURIComponent(name) + '=' + encodeURIComponent(value) + '&';
    }
      
    return query.length ? query.substr(0, query.length - 1) : query;
  };
 
  // Override $http service's default transformRequest
  $httpProvider.defaults.transformRequest = [function(data) {
    return angular.isObject(data) && String(data) !== '[object File]' ? param(data) : data;
  }];
});

用这种方法。没必要写这么多

 isAuth = $http.post("Yr URL", {username: username, password: password});

在nodejs的后端

app.post("Yr URL",function(req,resp)
{

  var username = req.body.username||req.param('username');
  var password = req.body.password||req.param('password');
}

我希望这对你们有帮助

我写了一个小的PHP帮助函数,允许这两种类型的输入参数:

function getArgs () {
    if ($input = file_get_contents('php://input') && $input_params = json_decode($input,true))
        return $input_params + $_POST + $_GET;
    return $_POST + $_GET;
}

用法:

<?php
    include("util.php"); # above code
    $request = getArgs();

    $myVar = "";
    if (isset($request['myVar']))
        $myVar = $request['myVar'];
?>

因此不需要修改JavaScript。

我使用asp.net WCF webservices与angular js和以下代码 工作:

 $http({
        contentType: "application/json; charset=utf-8",//required
        method: "POST",
        url: '../../operation/Service.svc/user_forget',
        dataType: "json",//optional
        data:{ "uid_or_phone": $scope.forgettel, "user_email": $scope.forgetemail },
        async: "isAsync"//optional

       }).success( function (response) {

         $scope.userforgeterror = response.d;                    
       })

希望能有所帮助。

这段代码为我解决了这个问题。它是一个应用级解决方案:

moduleName.config(['$httpProvider',
  function($httpProvider) {
    $httpProvider.defaults.transformRequest.push(function(data) {
        var requestStr;
        if (data) {
            data = JSON.parse(data);
            for (var key in data) {
                if (requestStr) {
                    requestStr += "&" + key + "=" + data[key];
                } else {
                    requestStr = key + "=" + data[key];
                }
            }
        }
        return requestStr;
    });
    $httpProvider.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
  }
]);