简体   繁体   中英

Angularjs: load contents from local json file

This is my code, I am trying to display the JSON contents, when I checked in console, the data which was getting returned was the whole html code, instead of json data. Where am i going wrong?

<html ng-app="BooksApp">

<head>
    <meta charset="utf-8">
    <title>Angular.js </title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
    <script>
        var BooksApp = angular.module('BooksApp', []);
        BooksApp.controller("BookCtrl", ['$scope', '$http', function ($scope, $http) {
            $http.get('books.json').success(function (data) {
                $scope.books = data;
                console.log(data);
            });
    }]);
    </script>
</head>

<body ng-controller="BookCtrl">
    <h2>Angular.js </h2>
    <table>
        <tr>
            <th>Book Name</th>
            <th>Book Price</th>
        </tr>
        <option ng-repeat="entry in books.books" value="{{entry.name}}">{{entry.name}}</option>
    </table>
</body>

</html>

books.json

{
    "books": [{
        "id": 2081,
        "name": "python",
        "price": "1000"
    }, {
        "id": 8029,
        "name": "c++",
        "price": "2000"
    }],
    "count": 2
}

截屏

app.js

var http = require('http'),
    fs = require('fs');


fs.readFile('./index.html', function (err, html) {
    if (err) {
        throw err; 
    }       
    http.createServer(function(request, response) {  
        response.writeHeader(200, {"Content-Type": "text/html"});  
        response.write(html);  
        response.end();  
    }).listen(8000);
});

AngularJS using to create SPA app, you need to run it separate from the backend. But it seem that you use node to serve the static file also want to get book.json from it.

The new approach:

The server side, just create an api that return book.json via api /books

var express = require('express');
var app = express();
fs = require('fs');

app.get('/books', function (req, res) {
    fs.readFile('books.json', 'utf8', function (err,data) {
        if (err) {
            return console.log(err);
        }
        console.log(data);
        res.send(data)
    });

})

app.listen(3000, function () {
    console.log('Example app listening on port 3000!')
})

The client side, call to that server

$http.get('http://localhost/books').success(function(data) {
   $scope.books = data;
   console.log(data);
});

I've noticed that this can happen when Angular isn't able to find the file specified in a $http.get() request. Also, the .success return from an angular $http.get() function has been deprecated. Instead, use the $http.get(...) .then way of doing this as stated in the angular documentation:

https://docs.angularjs.org/api/ng/service/ $http

You also may want to use an errorCallback as stated in the docs and output error information to the console - this may give you more information about what's happening.

Also, I don't know why you'd want to use the filesystem to read the ./index.html file rather than use a local (and free) webserver such as Apache. I doubt you'll have full access to the filesystem if you end up hosting your site on a hosted server.

https://httpd.apache.org/

Lastly, if you're just learning AngularJS, you may want to start with a sample project to see how Angular projects are structured such as the following official small seed project.

https://github.com/angular/angular-seed

Hope that helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM