using angular js with node js application example

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

Next: Using mongo db in the angular node js application

introduction to Angular js for usage of node js

This is a continuation of the tutorial started on node js angular and mongo db shown on
node js console tutorial

I might not go over the basics of angular js here except what is needed for the tutorial.

The main idea in using Angular js would be to make sure the front end and back end are completely separated and they would be talking each other through end points that are designated through node js.

Angular basics

Angular is an MVC architecture oriented javascript framework. I will have some example that would illustrate that as a basic introduction.


<html>
	<head><title>Testing angular</title></head>
	<body ng-app="HelloTest">
        
		<div ng-controller="HelloController">
			<p>{{concat}}</p>
		
            <div> <input type="text" ng-model="color" ng-keyup="updateColor()" name="color" /></div>
            <div> The selected color is {{current_color}} </div>
        </div>

	    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>  
        <script>
		    angular.module("HelloTest", []).controller("HelloController", function($scope){
                $scope.concat = "Whatever goes here";    
                $scope.updateColor = function () {
                    $scope.current_color = $scope.color;
                };
            });
	    </script>
    </body>
</html>

Save the above code in a file angular.html and just double click on it to see it running.

The above simple example shows a basic usage of events in Angular js. All it does is printing whatever you put in the text box as color.

Basic points in the Angular application

ng-app="HelloApp" : this would be assigned usually on the root of the html dom. It tells that pages is under the given ng-app. See how that name aligns with the name angular.module("HelloApp")

ng-controller The app can contain a number of controllers under it. A controller is the one that sits between the view and logic that would fill up the view. in this example, the ng-controller="HelloController" will be used for the directive it has been defined. In this example for the whole element of the div it has been declared for.

You can have as many controller as you want in the given app


//create the application here
var app = angular.module("HelloTest", []);

//create the controller.
app.controller("HelloController", function($scope){
                $scope.concat = "Whatever goes here";    
                $scope.updateColor = function () {
                    $scope.current_color = $scope.color;
                };
            });

//create another controller.
app.controller("AnotherController", function($scope){
                $scope.concat = "In another controller";    
            });

The above shows how you can have more than one controller in the app.

$scope is the special variable passed around that would give the whole scope that the controller has authority of.

the {{ }} is the place holder that would be assigned the value from the controller. In the example above, concat and current_color are the ones to be assigned from the controller and get their values being assigned where ever they are.

Angular has lots and lots of directives for the condition, loop and the like

Next: get the list of countries from node and showing them using Angular example

Using template engine in node js to render response values example

This is a continuation of the tutorial started on node js angular and mongo db shown on
node js console tutorial

In this tutorial, the user input was accepted and processed, but the result was not sent to another html page that contains the result.

In real world application that is common task, say if you have a page listing the name of countries by reading them from data source, the returned page should populate the list of countries with probably other information which is well formatted with css and even some javascripts.

For this, the node has provided the templating engine.

What the template engine does is, it will put some placeholders for the variables that are sent from the server, process them and will finally output html file.

There are many template engines out there for node, I have used ejs since it is easy to use and has similarity with HTML and javascript.

Using template engine in node js to render html pages

1. create a directory node-template

2. move to that directory and issue the following command to install express in it

sudo npm install express

3. The above command would install express package in node_modules folder. This is the folder where all third party packages would be stored.

4. install ejs template engine

sudo npm install ejs

5. create server.js in node-template folder and add the following code in it


var express = require("express");
var app = express();

app.set("view engine", "ejs");
app.set("views", __dirname + '/views');

//router for the home page
app.get("/", function(request, response){
   //this doesn't need anything to be rendered so it is provided simple html file
   response.sendFile(__dirname + '/views/index.html'); 
});

//router for listcountries path
app.get("/listcountries", function(request, response){
    var title = "List of Countries";
    //instantiate the list of countries from hard coded array
    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.render("countries", {'countries': hardCodedCountries, 'title': title});
});

app.listen(8080);
console.log("Hit http://localhost:8080");

From the above code, the part

app.set("view engine", "ejs");
app.set("views", __dirname + '/views');

Tells the node what template engine we are using and where the template pages are supposed to be residing. The __dirname is the current directory of the running script

Another point is, you see response.render that is where the ejs would be useful. It would take the countries list and iterate through them to display. The hardCodedCountries and title are computed values that are passed to the template file.

Further ejs syntax and usage can be seen here

6. Create file countries.ejs and add the following code in it.


<html>
<head><title>With template engine</title></head>
<body>
<h2><%= title %></h2>
<table>
<% for(var i=0; i<countries.length; i++) {%>
   <tr><td><%= countries[i].name %> </td>
        <td><%= countries[i].population %> million </td></tr>
   <% } %>
</table>
</body>
</html>

7. Then being in the node-template folder, run

node server.js

This would require, as you can see it, having the pages tightly coupled with the logic and that is not good.

What is needed for this then is, a separate front end from the nodejs

Next: Quick introduction to Angular js

how to get user input and process it in nodejs tutorial

This is a continuation of the tutorial started on node js angular and mongo db shown on
node js console tutorial

Now we have advanced a bit more and have served an html file from node js in this tutorial.

It would be a matter of updating the html file to have the user input box and adding one more route in node js to wait for specific url, getting the input and posting back the processed data.

In this part, the app will accept a name from the user and will print an email address containing the name that is provided.

How to get input from the user

If you have followed this tutorial, start from number 4

1. create a directory node-input

2. move to that directory and issue the following command to install express in it

sudo npm install express

3. The above command would install express package in node_modules folder. This is the folder where all third party packages would be stored.

4. create server.js file in the folder node-input and add the following snippet in it.


 var express = require("express");
 
 //use the application off of express.
 var app = express();
 
 //define the route for "/"
 app.get("/", function (request, response){
     response.sendFile(__dirname+"/views/index.html");
 });
 
 app.get("/getemail", function (request, response){
     var firstname = request.query.firstname;
 
     if (firstname != "") {
         response.send("Your email address is " + firstname + "@gullele.com");
     } else {
         response.send("Please provide us first name");
     }
 });
 
 //start the server
 app.listen(8080);
 
 console.log("Something awesome to happen at http://localhost:8080");

5. create a folder views in node-input folder

6. create index.html inside views and add the following code in it


<html>
    <head>
        <title>Simple hello world</title>
        <style>
            .prompt {
                font-size: 16px;
                color: brown;
                font-weight: bold;
                margin-bottom: 5px;
            }
            .container {
                width: 50%;
            }
            .left-pane {
                width: 50%;
                float: left;
            }
            .right-pane {
                width: 50%;
                float: right;
            }
            .submit-name {
                clear: both;
            }
        </style>
    </head>
<body>
    <h1>Hello Node JS</h1>

    <form method='GET' action="/getemail">
        <div class="container">
            <div class="prompt left-pane">
                <span>Give us your firstname and get email address</span>
            </div>
            <div class="right-pane">
                <input type="text" id="firstname" name="firstname" />
            </div>
        </div>
        <div class="submit-name">
            <input type="submit" value="get the email" />
        </div>
        </div>
    </form>
</body>
</html>

7. Save this file and start the sever using

node server.js

8. Now go to browser and surf http://localhost:8080

As you can see, the main point here would be adding one more route app.get("/getemail", function (request, response){ and accessing the parameters using the request object then passing the response with processed name in it.

The next would be to see how node can accomplish rendering the next page with values. And for that, there is a need to have template engine introduced.

Next: Using template engine ejs with node js

how to display html files from node js example tutorial

This is a continuation of the tutorial started on node js angular and mongo db shown on
node js console tutorial

Here We have see how to print a Hello World for a request of “/”. That is a good advancement but that won’t give us much to proceed. We need a way to server html files for different requests.

So, what we want to do is to have more flexibility by having html file. We will have all the contents as we wish using the old school html tag and we will serve that through node js.

Displaying and rendering html file through node js

If you have followed this then start from number 4

1. create a directory node-input

2. move to that directory and issue the following command to install express in it

sudo npm install express

3. The above command would install express package in node_modules folder. This is the folder where all third party packages would be stored.

4. create server.js file in the folder node-input.


 var express = require("express");
 
 //use the application off of express.
 var app = express();
 
 //define the route for "/"
 app.get("/", function (request, response){
     //show this file when the "/" is requested
     response.sendFile(__dirname+"/views/index.html");
 });
 
 //start the server
 app.listen(8080);
 
 console.log("Something awesome to happen at http://localhost:8080");

5. create a folder views in node-input folder

6. create index.html inside views and add the following code in it


 <html>
 <head><title>Simple hello world</title></head>
 <body>
 <h1>Hello Node JS</h1>
 </body>
 </html>

7. go to your browser and type http://localhost:8080

You will see Hello Node Js on the browser big and bold.

What is going on

It is like the previous example except we are serving the actual physical html file this time.

By doing so, we have more control on the html file like adding css and javascript codes or calling those files on the page.

Mind you, index.html is the entry point, once we got on that page, we can navigate to other pages and do more

**If the above app is not working for whatever reason, make sure to update npm and get newest version

npm i -g npm-check-updates
npm-check-updates -u
npm insert

Next: Accepting input from the user and processing it.

using express package in node – installation and usage example tutorial

This is a continuation of the tutorial started on node js angular and mongo db shown on
node js console tutorial

By far, you have seen how to write to the console and to display hello world through web using node.

But, showing simply Hello World is not that interesting and fun at all. And it doesn’t show anything that simulates real world example of accepting input from user and processing that.

Before doing that, lets see the express package which would enable us to do that.

installing express package and creating a page with input boxes.

1. create a directory node-input

2. move to that directory and issue the following command to install express in it

sudo npm install express

3. The above command would install express package in node_modules folder. This is the folder where all third party packages would be stored.

4. create server.js file in the folder node-input.

5. add the following code into server.js file.


 var express = require("express");
 var app = express();
 
 app.listen(8080);
 
 console.log("Something awesome to happen at http://localhost:8080");

6. Go to command line and start the web server, by now we know how to start the web server as

node server.js

Now you will see something interesting when you go to browser and type http://localhost:8080.

This time you would get Cannot GET / Unlike the previous time.

What is going on

express is framework that would make life way easier for the http communication between the nodejs server and whoever wants the request.

Among other things, it handle the http verbs, GET POST, DELETE, PUT, also it make the routing very easier. That is when you want to access some pages with something like http://gullele.com/list or http://gullele.com/register. That means the /list and /register are handles through routing mechanisms of express.

Ok, lets fix the that “Cannot GET /” error.

Update the server.js as follows

                                                                                                                                                                        
 var express = require("express");
 
 //use the application off of express.
 var app = express();
 
 //define the route for "/"
 app.get("/", function (request, response){
     response.end("Hello World");
 });
 
 //start the server
 app.listen(8080);
 
 console.log("Something awesome to happen at http://localhost:8080");

Now you will see Hello World on your browser when you type http://localhost:8080.

This time, we have created a router to response when the user lands on the root of the website.

Next: Serving html files from node js

node js mongo db and angular js tutorial for beginners from scratch

node js beginner guide with mongo and angular

node js step by step tutorial showing you how to create a full fledged node js angular js and mongo db for beginners who have never played with these technologies or played partially independently but not all those technologies together.

I assume installing nodejs to your computer can be found easily and I will not go through that.

Starting with a simple Hello world display with webserver

Node js is a fully functional webserver and processor that is created off of Googles V8 engine. It is very light weight and the syntax is javascript syntax.

Unlike other languages where you have to setup and configure a different independent webserver, node js, comes with a total self contained web server serving at ports that you can assign. Which makes it a full one stop web application.

For comparison, when working on php might require you to setup a different webserver like Apache or IIS.

In this part, I will show a very simple old school hello world example to be done in node js.

In the upcoming tutorials, you will see how to change those step by step.

Hello world in node js

1. Create a folder in your computer and name it as node-tutorial

2. in the node-tutorial folder create hello.js file

3 on hello.js add the following code in it.

console.log("Hello World");

Then save the above file and run the file as

node hello.js

This will print Hello World in the CONSOLE.

What did happen

The above code is running from the node js as a command line code. There is no any web server, that making it available through browsers per se, this time, it will just print that on right on the terminal you are running it.

You might know console.log() from your javascript coding and it is doing the same task here in node as well.

Next: Run Hello World using http through browser