angular.js - Angular 通过 $http.post 写入本地 JSON 文件
迷茫
迷茫 2017-05-15 16:49:59
0
3
754

最近在练习使用 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>

希望有朋友能够帮忙找下错误在什么地方,谢谢!

迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

reply all(3)
淡淡烟草味

I got help from the IRC on Angular’s ​​official website. The answer (translation) is roughly as follows:

file:/// 是本地简单的文本服务器,能够实现 $http.get() 的服务,但是要实行 POSTPUTDELETE 的服务,就需要真正的网络服务器了。如果你会多种语言的话,可选的种类有很多种,基于 PHPRailRubyJava Wait.
Of course, you can choose a full JS solution. For example, I am using it now MEAN. I wish you a happy play.

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?

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template