这是我对简单均值堆栈应用程序的实现
server.js
var express = require('express');
var app = express();
var mongojs = require('mongojs');
var db = mongojs('contactlistDB', ['contactlist']);
app.use(express.static(__dirname + "/public"));
app.get('/friendlist', function(req, res){
db.on('connect', function(){
console.log("DB connected !!!");
});
console.log("received GET request");
db.contactlist.find(function(err, docs){
res.send(docs);
});
});
app.listen(3000);
controller.js
var myApp = angular.module('myApp', []);
myApp.controller('AppCtrl', ['$scope', '$http', function($scope, $http) {
console.log("Hello World from controller");
$http.get('/friendlist').success(function(response){
$scope.friendList = response;
})
}]);
的index.html
<!DOCTYPE>
<html ng-app="myApp">
<head>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap-theme.min.css">
<title>Friends Information App</title>
<body>
<div class="container" ng-controller="AppCtrl">
<h1>Friend Information App</h1>
<table class="table">
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Number</th>
</tr>
<tr ng-repeat="friend in friendList"> <!-- same as for loop -->
<th>{{friend.name}}</th>
<th>{{friend.email}}</th>
<th>{{friend.number}}</th>
</tr>
</thead>
</table>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.12/angular.min.js"></script>
<script src="controllers/controller.js"></script>
</body>
</head>
</html>
我的路线肯定是/ friendlist但我不知道为什么,当我点击thr url http://localhost:3000时,所有朋友的信息都会显示在index.html文件中的UI中。当点击http://localhost:3000/friendlist时,我得到的只是没有UI的json普通文本
请帮我解释一下这个案例的工作流程。 非常感谢!
答案 0 :(得分:1)
当您点击http://localhost:3000时,您会访问包含所有UI内容的网页。点击http://localhost:3000/friendlist,您就会请求打印JSON对象的API。这是因为您使用行app.use(express.static(__dirname + "/public"));
通过API为您的html提供服务。这是一种正常的行为。
答案 1 :(得分:0)
First of all
app.get('/friendlist', function(req, res){
db.on('connect', function(){
console.log("DB connected !!!");
});
console.log("received GET request");
db.contactlist.find(function(err, docs){
res.send(docs);
});
});
it is called which redirects to the get method in /friendlist controller function.
Under that
$http.get('/friendlist').success(function(response){
$scope.friendList = response;
})
it is called and it gives the response in friendlist var. and it prints out the thing accordingly.