【问题标题】:$http.post not sending variables$http.post 不发送变量
【发布时间】:2016-01-18 06:25:00
【问题描述】:

我做错了吗?当我执行以下操作时,/url

中没有收到任何帖子变量
$http.post("/url", { something: "something" })
    .success(function(data) {
        console.log(data);
    }).error(function(data){ alert("An error occurred. Please try again."); }
);

【问题讨论】:

标签: angularjs angularjs-http


【解决方案1】:

默认情况下,角度将数据编码为Content-Type: application/json,但您希望它为Content-Type: x-www-form-urlencoded。后者由jQuery post 设置为默认值,这就是为什么大多数新人都会落入这个陷阱的原因。

所以你必须在发出请求之前设置内容类型。

yourApp.config(['$httpProvider', function($httpProvider) {
    $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
}]);

现在在每次 http 请求之前,内容类型都会更改为我们上面设置的内容。

post 讨论了相同的主题。

【讨论】:

    【解决方案2】:

    我遇到了与 HTTP 标头相关的类似问题,以下在所有情况下都适用于我。

    var data = {something: "something"};
    $http({
        method: 'POST',
        url: url,
        data: data,
    //Uncomment this if the problem persists, it's to explicitly state the content type.
        //headers: {'Content-Type': 'application/x-www-form-urlencoded'}
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-10-15
      • 1970-01-01
      • 2017-05-12
      • 2017-07-05
      • 1970-01-01
      • 2018-04-21
      • 2017-03-08
      • 2021-08-12
      相关资源
      最近更新 更多