Search code examples
angularjsnode.jsmean-stackangularjs-routing

Weird flow of simple mean stack application


Here is my implementation of simple mean stack application

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>

Definitely my route is /friendlist but I do not know why, when I just hit thr url http://localhost:3000, all my friends information are shown up with the UI in index.html file. And when hitting the http://localhost:3000/friendlist, what I got just the json normal text without UI

Please help to explain to me about the workflow of this case. Many thanks!


Solution

  • When you're hitting http://localhost:3000 you reach your web page which contains all your UI stuff. By hitting http://localhost:3000/friendlist, you're requesting your API which prints your JSON object. This is because you're serving your html by your API with the line app.use(express.static(__dirname + "/public"));. It's a normal behavior.