有人能告诉我为什么下面的语句没有将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对象发送吗?


当前回答

我在使用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;
  }];
});

其他回答

根据@felipe-miosso的回答:

从这里下载一个AngularJS模块, 安装它 将它添加到您的应用程序: Var app = angular。模块('my_app',[…], ' httpPostFix ']);

要通过Post方法和angularjs的$http发送数据,你需要改变

数据:"message=" +消息,数据:$.param({消息:消息})

我在快递上也遇到了同样的问题。为了解决这个问题,你必须在发送HTTP请求之前使用bodyparser来解析json对象。

app.use(bodyParser.json());

我通过以下代码解决了这个问题:

客户端(Js):

     $http({
                url: me.serverPath,
                method: 'POST',
                data: data,
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            }).
                success(function (serverData) {
                    console.log("ServerData:", serverData);
    ......

注意,data是一个对象。

在服务器端(ASP。NET MVC):

[AllowCrossSiteJson]
        public string Api()
        {
            var data = JsonConvert.DeserializeObject<AgentRequest>(Request.Form[0]);
            if (data == null) return "Null Request";
            var bl = Page.Bl = new Core(this);

            return data.methodName;
        }

和'AllowCrossSiteJsonAttribute'需要跨域请求:

public class AllowCrossSiteJsonAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Origin", "*");
            base.OnActionExecuting(filterContext);
        }
    }

希望这对你有用。

类似OP建议的工作格式和Denison的回答,除了使用$http。而不是$http,仍然依赖于jQuery。

在这里使用jQuery的好处是可以正确地传递复杂对象;反对手动转换为URL参数,可能会混淆数据。

$http.post( 'request-url', jQuery.param( { 'message': message } ), {
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
});