This is a continuation of the tutorial started on node js angular and mongo db shown on
node js console tutorial
Take a look on this tutorial and I will use the same setup with it
Follow until step 5 from the above example.
If you see the server.js, it will populate the hardcoded countries the template file countries.ejs
file.
But this time, we dont need the ejs file at all, rather all what is needed from the node js server is to provide the json formatted response of the countries.
In the server.js
file, add the following code
var express = require("express");
var app = express();
app.set("views", __dirname + '/views');
app.get("/", function(request, response){
response.sendFile(__dirname + '/views/index.html');
});
app.get("/listcountries", function(request, response){
var title = "List of Countries";
var hardCodedCountries = [{"name":"America","population":300}, {"name":"Britain","population":53},{"name":"Canada","population":35},{"name": "Democratic Congo","population":67},{"name": "Ethiopia","population":90}, {"name":"Finland", "population":5}, {"name":"Gabon", "population": 2}];
response.send(hardCodedCountries);
});
app.listen(8080);
console.log("Hit http://localhost:8080");
On this one, the view engine
is removed and also the response.render
is replaced by response.send
In short, the node has created an endpoint named /listcountries
that would list countries and send that to the requester.
6. Now, the next task would be to update the page that would list the countries using angular
update the index.html file in views folder as follows
<html>
<head><title>Node with template</title></head>
<body ng-app="AngularNodeApp">
<div ng-controller="CountryController">
<h2>Listing countries has never been easy</h2>
<a href="#" ng-click="listCountries()">List Countries</a>
<div>
<ul ng-repeat="country in countries">
<li>{{country.name}} | {{country.population}}</li>
</ul>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>
<script>
var app = angular.module("AngularNodeApp", []);
app.controller("CountryController", function($scope, $http){
//get the list of countries
$scope.listCountries = function() {
//call the API to listcountries and get the list of countries as json response
$http.get("/listcountries").success(function(countries_from_node){
//assign countries variable that is accessed through $scope
$scope.countries = countries_from_node;
});
};
});
</script>
</body>
</html>
Here it is clear that, the front and backend are separated in that the front end would act in its own by requesting what it needs from the backend only. As long as the node js is responding the list through its listcountries