【发布时间】:2016-04-29 19:47:15
【问题描述】:
我是 angular.js 的新手,无法让简单的 POST 请求正常工作。我正在使用角度版本 1.4.8。我的请求永远不会到达服务器。相反,它会在发出请求之前出现客户端错误。我看不出我做错了什么,即使我已经阅读了这里的文档:https://docs.angularjs.org/api/ng/service/$http#post。这是我拥有的相关错误信息(使用下面的代码示例生成):
{ “数据”:空, “状态”:-1, “配置”:{ “方法”:“发布”, “转换请求”:[ 空值 ], “转换响应”:[ 空值 ], "url": "http://localhost:4567/foo", “数据”: { “富”:“酒吧” }, “标题”:{ "Accept": "application/json, text/plain, /", “内容类型”:“应用程序/json;charset=utf-8” } }, “状态文本”:“” }
这是我的代码示例。它在 Firefox 和 chrome 中都重现了该问题,因此这似乎不是浏览器的怪癖。由于我是一个角度新手,这可能是基本的(但对我来说并不明显)。帮助表示赞赏;)
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
</head>
<body>
<script>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function ($scope, $http) {
$scope.httpPost = function (postBody) {
var successCallback = function (data, status, headers, config) {
alert("post success");
};
var errorCallback = function (data, status, headers, config) {
var responseJson = angular.toJson(data);
$scope.theError = responseJson;
};
$http.post('http://localhost:4567/foo', postBody).then(successCallback, errorCallback);
};
var postBody = {"foo" : "bar"};
$scope.httpPost(postBody);
});
</script>
<div data-ng-app="myApp" data-ng-controller="customersCtrl">
<pre>{{theError}}</pre>
</div>
</body>
</html>
【问题讨论】:
-
您能否提供有关客户端错误的更多信息?你在这两个回调中得到了什么吗?
-
我将错误转换为 json。它列在问题的第二段中。
-
我的意思是,你打印了 $scope.theError 吗? (只是确保因为它看起来像你这样做)或者错误来自哪里?确保它是客户端错误,因为您发布的 JSON 看起来请求很好/您的代码看起来不错
-
错误是用这一行打印出来的:
{{theError}}