I am new to angular.js and am unable to get a simple POST request to work. I am using angular version 1.4.8. My request never makes it to the server. Instead, it appears the client errors out before making the request. I can't see what I'm doing wrong, even though I've read the documentation here: https://docs.angularjs.org/api/ng/service/$http#post. Here is the relevant error info I have (produced with the code example below):
{ "data": null, "status": -1, "config": { "method": "POST", "transformRequest": [ null ], "transformResponse": [ null ], "url": "http://localhost:4567/foo", "data": { "foo": "bar" }, "headers": { "Accept": "application/json, text/plain, /", "Content-Type": "application/json;charset=utf-8" } }, "statusText": "" }
And here is my code example. It reproduces the problem in both firefox and chrome, so this doesn't seem to be a browser quirk. Since I'm an angular newbie, this is likely something basic (but not obvious to me). Help appreciated ;)
<!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>