Reputation: 807
I am new to Angular. I am learning about the $http service and currently trying to send JSON data via POST. Unfortunately, I am getting an error. I tried reading other people's posts concerning this problem, but I can't seem to understand what the issue is.
Can anyone help me understand why I am getting this error and suggest ways of fixing it ?
HTML
<!DOCTYPE html>
<html ng-app = "app">
<head>
<title></title>
</head>
<body ng-controller = "ctrl">
<form>
<input type="text" ng-model = "newDJ_name">
<button ng-click = "addDJ(newDJ_name)">Add new DJ name</button>
<button ng-click = "show()">Show DJs</button>
</form>
<div ng-repeat = "dj in djs">
{{dj.name}}
</div>
</body>
<script src = "angular.min.js"></script>
<script src = "httpService.js"></script>
</html>
Javascript
var app = angular.module ("app",[]);
app.controller ("ctrl",function ($scope,$http) {
$scope.show = function () {
$http.get('djs.json').success(function(data){
$scope.djs = data;
})
};
$scope.addDJ = function (newName) {
$http.post('http://localhost:8080/Documents/Angular/djs.json',{name : newName})
.success(function(data) {
$scope.djs = data;
})
.error (function(data) {
console.log(":(");
})
}
});
JSON file
[{
"name": "Adam Beyer",
"city": "Sweden",
"genre": "techno",
"label": "Drumcode"
}, {
"name": "Richie Hawtin",
"city": "Detroit",
"genre": "techno",
"label": "Minus"
}, {
"name": "Solomun",
"city": "Undefined",
"genre": "techno",
"label": "Dyinamic"
}]
When I try to add a new dj name
Upvotes: 0
Views: 1628
Reputation: 5762
You are trying to make POST your data directly to a .json file. This is not possible.
Instead, write a webservice endpoint on your server that: -Accepts the 'POST' phrase and payload data -Writes the data to a file, in your case, a .JSON file -Returns a meaningful response back to your Angular app, based on the success or failure of creating the file.
Note - if you are trying to update a .JSON file that already contains data, you will probably need to parse the existing file as JSON, mutate it with the new data, then save it back to the file.
If you were to change the webservice phrase to GET, you should typically see a successful response:
// This will work
$http.get('http://localhost:8080/Documents/Angular/djs.json')
Upvotes: 1