Adding Routes to Your Server: Node.js

With this video tutorial, lets learn about testing our code snippets using REPL, before implementing it into the actual node application. And then, we’ll show you how to add routes to your node server.

routes-node-server-request-response

In this tutorial, we create 5 routes to the server:
“/” to “Home Page”
“/about” to “About Us”
“/contact” to “Contact Us”
/”satish” redirected to “Home Page”
anything else to “Page Not Found”

Command Prompt
Console Window

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
C:\>node
> var url = require("url");
undefined
> var myURL = "http://Technotip.org:3030/about";
undefined
> url
{ parse: [Function: urlParse],
  resolve: [Function: urlResolve],
  resolveObject: [Function: urlResolveObject],
  format: [Function: urlFormat],
  Url: [Function: Url] }
> url.parse(myURL).hostname;
'technotip.org'
> url.parse(myURL).port;
'3030'
> url.parse(myURL).pathname;
'/about'
>

Here we test our code snippets on the command prompt, before implementing it into our actual application. Working with node url module on command prompt, we learnt to make use of parse() method of url object to fetch the hostname, port and the pathname of the actual URL. We are interested in pathname – we’ll be using it in our node application.

Related Read: Read Evaluate Print Loop (RELP): Node.js

JavaScript File
app.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
var url= require("url");
var http= require("http");
 
     http.createServer(function(req, res){
 
var pathname= url.parse(req.url).pathname;
 
if( pathname === '/' )
{
res.writeHead(200, { "Content-Type": "text/plain" });
res.end("Home Page");
}
else if( pathname === '/about' )
{
res.writeHead(200, { "Content-Type": "text/plain" });
res.end("About Us");
}
else if( pathname === '/contact')
{
res.writeHead(200, { "Content-Type": "text/plain" });
res.end("Contact Us");
}
else if( pathname === '/satish' )
{
res.writeHead(301, { "Location": "/" });
res.end("Home Page");
}
else
{
res.writeHead(404, { "Content-Type": "text/plain" });
res.end("Page Not Found!!");
}
   }).listen("8080", "127.0.0.1");
 console.log("Server running ..");

Here we require url and http module. Using http object we create HTTP Server. Using url object we call parse method to parse and fetch the path from the user request URL.

Once we fetch the path, using conditional statements we display the corresponding message with appropriate response header information. We also illustrate 301 redirection

Adding Routes to Your Server: Node.js


[youtube https://www.youtube.com/watch?v=ejER-HVhDm8]

YouTube Link: https://www.youtube.com/watch?v=ejER-HVhDm8 [Watch the Video In Full Screen.]



Note: Make sure to turn on the server before trying to access the server!
execution code
command prompt

1
2
3
4
5
 
C:\>cd node
 
C:\node>node app.js
Server running ..

Navigate to the folder where you’ve your app.js file located, and run the server by executing the script using node command.

Network I/O Is Unpredictable: Node.js

We’ve seen the importance of callback method in our previous video tutorials. Now lets see how networked I/O Is unpredictable.


http-module-get-method-nodejs-network-io-unpredictability

Here we request/ping for information from 3 different servers and look at its response time. Each time we send a request, we get different response time depending upon how busy the server is, its bandwidth etc.

JavaScript File
app.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
var http= require("http"),
      urls  = [ "technotip.org",
         "technotip.com",
      "www.capturecaption.com"
       ];
 
for(var i = 0; i < urls.length; i++){
ping( urls[i] );
}
 
function ping( url ){
var start = new Date();
 
http.get({ host: url }, function(res){
console.log("URL :"+url);
console.log("Response Time: "+(new Date() - start)+" ms");
});
}

Here we require http module, which is built into nodejs, and store it inside a local object called http. We also declare and initialize an array with 3 domain names. Using for loop, we loop through each URL present in the urls array and pass it to a method called ping();

Inside ping method, we record client system date in a variable before sending a request to the server(via URL). Now using http objects get method we send request to the server and see it’s response time. get method takes 2 parameter, first parameter is an object which contains host information – the host url { host: url }. Second parameter is a callback method which automatically gets an object which is returned by first parameter {host: url}. Inside the callback method, we subtract the new system date with the one we recorded before requesting for a response, this way we calculate the response time of each URL.

HTTP get method: Node.js


[youtube https://www.youtube.com/watch?v=vktKMtWoPbA]

YouTube Link: https://www.youtube.com/watch?v=vktKMtWoPbA [Watch the Video In Full Screen.]



output
C:\node>node app.js
URL :technotip.com
Response Time: 1462 ms
URL :www.capturecaption.com
Response Time: 1993 ms
URL :technotip.org
Response Time: 2004 ms

C:\node>node app.js
URL :technotip.com
Response Time: 1381 ms
URL :www.capturecaption.com
Response Time: 1702 ms
URL :technotip.org
Response Time: 1871 ms

C:\node>node app.js
URL :technotip.com
Response Time: 1409 ms
URL :www.capturecaption.com
Response Time: 1628 ms
URL :technotip.org
Response Time: 2001 ms

C:\node>node app.js
URL :technotip.com
Response Time: 1512 ms
URL :www.capturecaption.com
Response Time: 1534 ms
URL :technotip.org
Response Time: 1899 ms

Each time we execute the script, we get different response time, and the order of URLs may also differ, as we can’t predict which server will respond first.

HTTP Server(request/response) Counter Application: Node.js

This video tutorial is a rapid application development to illustrate HTTP Server(request/response) using Node.js

In this video, we use HTTP Server(request/response): Node.js code and work on it to develop a simple counter application.

Using this application, we can know how many visits have been made since the last server down time!

For explanation of all the keywords and working, please visit HTTP Server(request/response): Node.js

HTTP Server
count.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
 var http = require('http');
 var visits = 0;
 
 http.createServer( function(request, response) {
 
console.log('New Connection');
visits++;
 
response.writeHead(200, { 'Content-Type':'text/plain' } );
response.write('Hello\n');
response.write('We have had '+visits+' visits');
response.end();
 
 }).listen(8080);
 
 console.log('Server Started..');

Here we take a variable called visits and initialize it to 0.
Once there is a new connection request, we increment it’s value by 1.
Since there is also request from favicon, practically, there’ll be 2 requests simultaneously: hence the counter increments by 2 for each new connection request.

using write method, we print the number of visits.

HTTP Server(request/response) Counter Application: Node.js


[youtube https://www.youtube.com/watch?v=yRaMJy5Mot0]

YouTube Link: https://www.youtube.com/watch?v=yRaMJy5Mot0 [Watch the Video In Full Screen.]



Output:
Hello
We have had 3 visits

Note:
Once you stop the server or whenever there is down time in the server, the counter is reinitialized once the server is restarted.

Make use of Database to store the counter value, if you need it inspite of server downtime or restarts.

HTTP Server(request/response): Node.js

This video tutorial illustrates working of simple HTTP Server, using Node.js
We’ll show the request, response of our HTTP server using simple Node.js program.

We’ll create a HTTP Server, with some response text in it.
Then, send request using web browser and see to that our HTTP server responds appropriately.

HTTP Server
hello.js(using chaining of methods)

1
2
3
4
5
6
7
8
9
10
11
var http = require('http');
 
http.createServer( function(request, response){
 
 response.writeHead(200, { 'Content-Type': 'text/plain' });
 response.write('Welcome to Node!');
 response.end();
 
}).listen(8080);
 
console.log('Server Started');

OR

hello.js(without using chaining of methods)

1
2
3
4
5
6
7
8
9
10
11
12
13
var http = require('http');
 
var server = http.createServer( function(request, response){
 
 response.writeHead(200, { 'Content-Type': 'text/plain' });
 response.write('Welcome to Node!');
 response.end();
 
});
 
server.listen(8080);
 
console.log('Server Started');

In the first line, we require http module of node.js
http module is built into node.js package, to help build node.js applications.

Using this http, we’ll call createServer method, which returns an object. Using this object we’ll call another method listen and pass port number 8080 to be(reserve to be used) used to invoke our HTTP server.

createServer method takes a anonymous function as parameter.

Anonymous function: Method with no name.

This anonymous method takes two parameters: request and response.

request and response: These are two objects passed by our http server when it receives new connection requests.

Using response object we’ll call writeHead method and pass 2 parameters.
First being the status code: 200 (which means, everything is ok or successfully connected)
Second parameter specifies that, the content type is plain text.

Inorder to demonstrate that our HTTP server is indeed responding/working, we’ll output a simple string “Welcome to Node” onto our web browser, as a response text.

Using the object returned by createServer method, we’ll invoke another method called listen and then reserve port number 8080 for our HTTP Server request.

Server Start
To indicate the server start, using simple console.log we’ll indicate its start.

node-http-server-start

Server Start
Command Prompt

1
node hello.js

Navigate to the folder where hello.js file is located. Now using node command execute hello.js file.

Once “Server Started” message is given, open any web browser and goto localhost:8080 to ping / request our HTTP server.

HTTP Server ( Request / Response ): Node.js


[youtube https://www.youtube.com/watch?v=9DFbfXcSIOw]

YouTube Link: https://www.youtube.com/watch?v=9DFbfXcSIOw [Watch the Video In Full Screen.]



Output:
Welcome to Node!

Note:
If you make changes to the response text(as in our example), you’ll need to restart the server in order for the changes to reflect at the client end.

Close the server connection using ctrl+ c and restart it using node command followed by file name.