search

Home  >  Q&A  >  body text

angular.js - Angular writes local JSON file via $http.post

I was practicing using Angular recently and encountered a problem when implementing $http to read and write local JSON documents.

Question

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:

1

2

<code> Failed to load resource: the server responded with a status of 404 (Not Found)

</code>

The key code is posted:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

<code>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}));

        });

    }

});

</code>

The corresponding HTML document for

is:

1

2

3

4

5

6

7

8

9

10

11

12

<code><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>

</code>

I hope someone can help me find the error, thank you!

迷茫迷茫2878 days ago825

reply all(3)I'll reply

  • 淡淡烟草味

    淡淡烟草味2017-05-15 16:51:59

    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………………

    reply
    0
  • 滿天的星座

    滿天的星座2017-05-15 16:51:59


    I transferred the json post method above and returned the result correctly

    reply
    0
  • 迷茫

    迷茫2017-05-15 16:51:59

    What should be written in books.json?

    reply
    0
  • Cancelreply