I was practicing using Angular recently and encountered a problem when implementing $http to read and write local JSON documents.
The content of the JSON document was successfully read out using the GET method; But when using POST to insert the local JSON document newBook, the following error occurred in the Chrome terminal:
Failed to load resource: the server responded with a status of 404 (Not Found)
var bookLibraryApp = angular.module('bookLibraryApp', ['ngRoute']);
bookLibraryApp.controller('BookLibraryController', function($scope, $http){
$http.get('api/books.json').success(function(data){
$scope.books = data;
}).error(function(){
alert("an unexpected error ocurred!");
});
$scope.addBook = function(){
var newBook = {
isbn: $scope.newBook.isbn,
title: $scope.newBook.title,
year: $scope.newBook.year
};
$http.post('api/books.json', newBook).success(function(){
$scope.msg = 'Data saved';
}).error(function(data) {
alert("failure message:" + JSON.stringify({data:data}));
});
}
});
The corresponding HTML document for is:
<p class="container">
<h2>Create a Book here</h2>
<p class="createBookInfo">
<p>ISBN: <input type="text" ng-model="newBook.isbn"/></p>
<p>Title: <input type="text" ng-model="newBook.title" /></p>
<p>Year: <input type="number" ng-model="newBook.year" /></p>
</p>
<br />
<button ng-click="addBook()">Insert this book</button>
<p>{{msg}}</p>
</p>
I hope someone can help me find the error, thank you!
I got help from the IRC on Angular’s official website. The answer (translation) is roughly as follows:
Okay, now the question comes, let’s discuss where the technology is stronger………………
I transferred the json post method above and returned the result correctly
What should be written in books.json?