Routing Without Express

Introduction

Today we are going to learn how routing works. In my previous article of Node.JS I have covered basics knowledge and how to start with Node.JS. If you don’t have basic idea of Node.JS please refer my previous article. All About Node.JS

This article covers the following areas
What is Routing?
Create Server
Example of Routing

What is Routing?

Routing is the mechanism by which requests (as specified by a URL and HTTP method) are routed to the code that handles them.

Prerequisites

Basic knowledge of
Node.JS

Create Server

To create a Node.JS server, here is few simple steps to follow:
Create NodeJSRouteApp folder.
In above folder create app.js file.

const http=require('http');
const port=3000;
const server=http.createServer((req,res)=>{
res.statusCode=200;
res.setHeader('Content-Type', 'text/html');
res.write('<h1>Hello World<h1>'); //write a response
res.end();
});
server.listen(port,()=>{
console.log('Server is running at ',port);
});

Now to run your node server run the command in your terminal
>node app.js
you will see “server is running at 3000” message in your terminal.
now go to your browser window and type URL http://localhost:3000/ you will see

 

Yehh😁! Our Node.JS server create successfully.

Let’s observe the output more deeply
Just right click on browser window and select inspect or you can just have  pressed f12 key
Go to Network tab
Select name localhost

It will give us all information like header, response etc.
In header tab we can see
Request URL- http://localhost:3000/
status code which is 200 means OK.
Request method – GET
Response Header contains Content-type: text/html


If you select Response tab you can see our message- ‘Hello World’



Now let’s finding the problem with URL http://localhost:3000/
If we add anything after above URL like http://localhost:3000/home/profile/
It will always show output Hello World

Oops😶! This is something which we don’t want.🤦‍♀️
Need to think some solution for this🤔
Let’s log req parameter to check what it gave us.

const server=http.createServer((req,res)=>{
res.statusCode=200;
res.setHeader('Content-Type', 'text/html');
res.write(<h1>Hello World<h1>'); //write a response
console.log(req)
res.end();
});


 

Ohhh, look what I found😃. Using URL, we can restrict other endpoints or path not to be hit.

Let’s add routing to avoid this problem into app.js file

const http = require('http');
const port=3000;
const server=http.createServer((req, res) =>{
    res.statusCode=200;
    res.setHeader('Content-Type', 'text/html');
    let url = req.url;
    if(url ==='/home'){
    res.write('<h1>Just Compile<h1>');
    res.end(); 
    }
    else if(url ==='/about')
    {
     res.write(`Just Compile believes in team work.
        Irrespective of project size they believe 
        in executing every project as a team. 
        They have a team of highly qualified 
        engineers with each specializing in their own 
        field like designing, testing and development.`);
     res.end();
   } 
   else if(url ==='/contact')
   { 
    res.write('<h1>contact us page<h1>');
    res.end(); 
   } 
  else
   { 
   res.write('<h1>404 Page<h1>'); 
   res.end(); 
   } 
}); 
server.listen(port,()=>{ 
console.log('Server is running at ',port); 
});

Finally, let’s run our server from the command line and see if it works! Let’s type  name of our server, port and corresponding endpoint(path) in our browser:
Now if we add URL http://localhost:3000/home
It will navigate you on below page

http://localhost:3000/about

http://localhost:3000/contact

If you enter other than above route like http://localhost:3000/fb
You will end up with 404 Page

 

Cool, now this is something which we want.😎

So, today we have learned how to route through multiple endpoints without express.

I hope this article will help you. Please put your feedback using comment which helps me to improve myself for next post. Thank You!

Please follow and like us:

All About Node.JS

Introduction

Now a day, Node is the fastest growing open source platform in the world. If you are wondering what Node.JS is and why is it so popular? so today, I am here to give you brief introduction about it.

This article covers the following areas of Node.JS.
Before starts with Node.JS
What is Node.JS
Why is it so popular?
Installation of Node.JS and NPM
Node Package Module (NPM)
Package.json
Example

Prerequisites

Basic knowledge of
HTML
JavaScript

Before starts with Node.JS

Common task for web server is to open a file on the server and return content of that file to the client.
Web applications written in a client- server model where
 The client would request for the file from the server and the server would respond with that file and close the connection after each response.

Now the question is, how server respond to millions of requests which is coming at the same time?
Lets Consider one example of ticket counter,
In ‘xyz’ station have only one ticket counter. When passenger count is increases its difficult to handle all passengers.Passengers would have to wait.
Solution for this problem is to increase ticket counters.
Here’s the concept coming named as Threads.

But this is not a good solution. Because, there is some point when request count is increases and each request is starting with new thread. Problem with this is, it consumes lots of memory and resources.

Yehhh😎, Now Here’s the time when Node.JS come

What is Node.JS?

Node.JS is runtime environment for executing JavaScript code outside of a browser. It is built on Google Chrome’s JavaScript Engine also known as V8 Engine.

Hmm, question raised in your mind right?🤔
So, what actually is a JavaScript Engine?

V8 is a powerful open source JavaScript engine provided by Google. It is a program that converts JavaScript code into machine code that microprocessors can understand.

Node.JS is not a framework and also not a programming language. Node.JS can use for building back-end services like APIs.

How Node.JS Works?

A Node.JS app is run by single process, without creating a new thread for     every request.
While performing I/O operations, when the response comes back Node.JS resume the operations instead of blocking the thread.
This allows Node.JS to handle thousands of request with single server.

This all possible because of Event Loop
Now the question is What is Event Loop?🤔
It is a program that waits for events and dispatches them when they happen

Why Node is so popular?

1] Single Programming Language for both Front-End and Back-End.
Most important reason to use Node.JS is It uses JavaScript everywhere so it’s easy for a JavaScript programmer to build back-end services using Node.JS
2] Fast
Node.JS is built on top of the Chrome JavaScript Engine. It is Non-Blocking Input/output means it can read data and send it back very fast.
3] Used on Multi-Platform
It has a real cross-platform language which allows Node.JS to be used on Mac, Windows, and Linux.

Installation of Node.JS and NPM

Installation steps:
1. Download the installer from Node.JS official website
2. Run the installer.
3. Now, test Node.JS version using the following command.
> node –v
v11.0.0

4. To test NPM version
> npm –v
6.4.1

Node Package Module

NPM is the package module which helps JavaScript developers load dependencies effectively. Following command used to load dependencies.
> npm install

This command is finding a json file named as package.json in root directory to install all dependencies defined in the file.
Package.json look something like below
{
"name": "NodejsApp",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node app"
},
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.16.4",
"mongoose": "^5.4.8"
}
}

The most important things in your package.json are name and version. Those are actually required, and your package won’t install without them.

Script
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node app"
},

If there is a app.js file in the root, then npm will default the start command to node app

Dependencies
"dependencies": {
"express": "^4.16.4",
"mongoose": "^5.4.8"
}

Dependencies are specified in a simple object that maps a package name to a version range.

Example of Node.JS Application

Let’s Starts for doing some code😊
To create Node.JS application follow below listed steps:
Import required modules
Create server.
Read request and return response

Let’s create app.js file
const http=require('http');
const port=3000;
const server=http.createServer((req,res)=>{
res.statusCode=200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World');
});
server.listen(port,()=>{
console.log('Server is running at ',port);
});

1] http
On the first line, we required the HTTP module. The module provides as interface to deal with http operations.

This is how we import modules
const http=require(‘http’);

2] create server
we call the createServer() method which will helps to creates a server.
const server=http.createServer((req,res)=>{
res.statusCode=200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World');
});

It will create server with response having status code 200, content type plain text and ‘Hello World’ response which is server sends to the browser. The request and response objects have information about incoming request and outgoing responses.

3] Read request and return response
After creating server, now it’s time to assign port number.
server.listen(port,()=>{
console.log('Server is running at ',port);
});

Here, the server listens to localhost on port 3000 and log “Server is running at 3000” in command prompt.

It’s time to run our app.js file.

Type url http://localhost:3000/ in the browser, to display Hello World string as shown on the screen below :

Congrats😄

You now know how to create Simple Node.JS app 😄

I hope this article was helpful for you. If it was, please leave a comment and clap it up! Thank You!

Please follow and like us: