最近在练习使用 Angular,在实现 $http 对本地 JSON 文档读写的时候遇到了问题。
使用 GET 方法成功将 JSON 文档的内容读出来;但是在使用 POST 插入本地 JSON 文档 newBook 的时候,Chrome 的终端里出现了如下错误:
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}));
});
}
});
对应的 HTML 文档为:
<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 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?