Angularjs:从本地json文件加载内容

时间:2023-01-24 09:36:15

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?

这是我的代码,我试图显示JSON内容,当我在控制台中检查时,返回的数据是整个html代码,而不是json数据。我哪里错了?

<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.json

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

Angularjs:从本地json文件加载内容

app.js

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

2 个解决方案

#1


4  

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.

AngularJS使用创建SPA应用程序,需要将其与后端分开运行。但似乎你使用node来提供静态文件也想从中获取book.json。

The new approach:

新方法:

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

服务器端,只需创建一个api,通过api / books返回book.json

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

#2


1  

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:

我注意到,当Angular无法找到$ http.get()请求中指定的文件时,就会发生这种情况。此外,不推荐使用角度$ http.get()函数返回.success。相反,使用$ http.get(...)。然后按照角度文档中的说明执行此操作:

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

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.

您还可能希望使用docs中所述的errorCallback并将错误信息输出到控制台 - 这可能会为您提供有关正在发生的事情的更多信息。

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.

另外,我不知道你为什么要使用文件系统来读取./index.html文件,而不是使用Apache等本地(和免费)网络服务器。如果您最终在托管服务器上托管您的网站,我怀疑您是否可以完全访问文件系统。

https://httpd.apache.org/

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.

最后,如果你刚刚学习AngularJS,你可能想从一个示例项目开始,看看Angular项目的结构如下面的官方小种子项目。

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

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

Hope that helps.

希望有所帮助。

#1


4  

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.

AngularJS使用创建SPA应用程序,需要将其与后端分开运行。但似乎你使用node来提供静态文件也想从中获取book.json。

The new approach:

新方法:

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

服务器端,只需创建一个api,通过api / books返回book.json

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

#2


1  

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:

我注意到,当Angular无法找到$ http.get()请求中指定的文件时,就会发生这种情况。此外,不推荐使用角度$ http.get()函数返回.success。相反,使用$ http.get(...)。然后按照角度文档中的说明执行此操作:

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

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.

您还可能希望使用docs中所述的errorCallback并将错误信息输出到控制台 - 这可能会为您提供有关正在发生的事情的更多信息。

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.

另外,我不知道你为什么要使用文件系统来读取./index.html文件,而不是使用Apache等本地(和免费)网络服务器。如果您最终在托管服务器上托管您的网站,我怀疑您是否可以完全访问文件系统。

https://httpd.apache.org/

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.

最后,如果你刚刚学习AngularJS,你可能想从一个示例项目开始,看看Angular项目的结构如下面的官方小种子项目。

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

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

Hope that helps.

希望有所帮助。