$ http.post不发送变量

时间:2016-01-17 22:15:02

标签: angularjs angularjs-http

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

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

2 个答案:

答案 0 :(得分:0)

默认情况下,角度将数据编码为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中讨论了相同的主题。

答案 1 :(得分:0)

我遇到了与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'}
})
相关问题