Understanding routing of expressJS in Node.JS

For further advanced reading you may want to prefer REST API using express .

I have started learning Node.JS and for web apps most popular ExpressJS framework. Well few call it big library as well. As learner does not matter whether big library or framework, let’s start exploring.

While exploring express realised that one of the most vital concept of express is Routing. In this post I will try to share my learning on express Routing with you. If you are starting with Express feel free to have a look on Setup Express and run first application in Node.js .

Let us assume that you have created first site using express. In root folder you will find App.js file. Go ahead and open App.js. In top you will find two modules express and http are imported along with other modules.

clip_image001

 

Express uses HTTP verbs to perform routings hence HTTP module is imported and of course to work with express framework express module is imported. Since express routes are based on HTTP verbs so method names are also matched. Refer following table for same.

clip_image003

You can create a route as below,

 

clip_image004

 

Above route will be accessed using HTTP GET on application being accessed on base address. As shown below you can see that plain text is sent in response object from express application.

clip_image005

In Express if you have two route paths with same address rather throwing error it will pick route path defined first in App.js

Assume you want to pass parameter while doing HTTP GET operation in above route then you have two choices. Either create two routes as shown below.

clip_image007

Second route will be accessed when a parameter will be passed while performing HTTP GET. So if you access application as below you will get served from second route path.

clip_image008

You may want to create only one route path making id as optional. Id can be make optional by putting it inside : id? This can be done as below,

clip_image010

Route path created above can handle both types of request either with parameter or without parameter. We are checking for the parameter and on basis of that different response being delivered. So bottom line is combination of 😕 makes parameter optional.

Express converts a route to regular expression internally. Input parameter can be parsed using req.params.id where is name of the parameter.

You can pass more than one parameters as shown below. We are making op as optional by placing it inside : ?

clip_image012

With second optional parameter application can be fetched as below. As you see we are passing id and op both while doing HTTP GET.

clip_image013

Express allow you to created REST based route path using *. So if I want to pass any number of parameters doing HTTP GET that can be done appending *

clip_image014

You can pass any number of parameters to access above created route path now.

clip_image015

If you try to access route which is not created then you will get error message as below. loo route is not there in rout paths so express is throwing error as below,

clip_image016

You can create routes with other HTTP VERBS . Method names are matched with HTTP verbs as discussed in beginning of this post.

clip_image017

You can test other operations like PUT , DELETE , POST in fiddler. This is how you can work with routing in express. For further advanced reading you may want to prefer REST API using express . Do not get overwhelmed with Visual Studio there in this post and follow the post to create REST API in any of your favourite code editor. I hope this post is useful to you.

If you want to create routes using crossroads then this post may help you

Create a Router in Node.js using crossroads

Chance to get free Access to Dan Wahlin AngularJS jump start course worth 60$

Winners will be announced on 3rd April 2014 Thursday at 8 am IST

Get 50% discount on course here

clip_image002

Dan Wahlin is well known blogger and speaker and he has been teaching us various technologies for several years now. You must have seen his many courses on HTML, JQuery, and JavaScript, AngularJS etc. on Pluralsight . Recently he published jump start course on AngularJS on Udemy.com.

You can find detail of course here .

This course is broken down into 6 modules with each module providing source code. Six modules are as follows,

  1. AngularJS – The Big Picture
  2. Views, Directives and Filters
  3. Controllers, Scope and Modules
  4. Routing
  5. Services and Factories
  6. Animation

You can find more information about course here and can buy also.

Get 50% discount on course here

Now I have a good news that Dan was very kind to give me 10 free access to this course. You may get free access to course in either of below mentioned three ways.

Option # 1

Put as comment of this blog post that why you should be given free access to course. Do not forget to mention your Email in comment such that I can contact you further.

 

Option # 2

Tweet about the course. Tweet with hashtag #angulardan. Do not forget to include URL of the course in your tweet. URL of course is given below,

https://www.udemy.com/angularjs-jumpstart

Optionally you can mention me in your tweet also. My twitter handle is @debug_mode

 

Option # 3

Comment on FaceBook update about this post on my page. You can find Facebook update at below URL

https://www.facebook.com/dhananjay.kumar.73113528/posts/10203577934631879?stream_ref=10

I will choose 10 random people from comment, twitter and Facebook to give away free access to course.

Winners will be announced on 3rd April 2014 Thursday at 8 am IST. Good luck J

Get 50% discount on course here

Setup Express and run first application in Node.js

In this post we will take a step by step look in setting up Express and creating first application. I assume that you have already installed Node. If not then go ahead and install from here

Once node.js is successfully installed, you can install Express framework by running npm install express on command prompt.

clip_image001

After installing express, I will recommend to create a new folder and change directory to newly created folder. I have created a folder expressjs and going to create a site named mysite using express framework. To create site run command express mysite . mysite is name of the site.

image

On successful execution of above command you will get suggestion as below that several files has been created.

clip_image003

Next to install dependency. To install that navigate to site directory. You can navigate to site directory using cd mysite. In mysite directory

clip_image004

It will install all dependency in mysite directory.

clip_image005

After successful installation of dependency you should get npm info ok message as shown in above figure. Now you can run created website by express using node.

clip_image006

In browser navigate to server on port 3000 and you will get basic site created using express up and running.

clip_image007

This is how you can set up express to create sites running on node.js. In further posts we will look into routing, app.js, routing path, http verbs. I hope you like this post. Thanks for reading.

Completed 6 years in Software Industry

image

 

24th March is very important date in my life. I started my journey as professional or in simple words I started working on 24th March 2008 after passing engineering in June 2007. Hence today I have completed 6 years as working professional. This has been an exciting journey. In these 6 years, I worked on various projects, under different managers, in three different companies in three different cities. When I look back, I find myself different than what I was on 24th March 2008. I must say this journey has changed me lot.

I have worked for these three companies so far,

image

On 24th March 2008 I joined UST Global as trainee Software Engineer and worked there till September 2010.

On 10th October 2010 joined Infosys as Senior System Engineer and worked there till June 2012.

On 2nd July 2012 joined Telerik as Developer Advocate and since then working here.

If you are reading this post then you must be knowing that I love to share my learning via my blog. I love blogging and I am sure you also (in case if you) love me for my blog and articles. In last 6 years my journey of blogging is as below,

 

image

 

Clearly seeing above chart you can conclude that I am getting old and momentum of writing posts are getting reduced. Oh God! Help me! I promise to meet your expectation and product quality posts in regular interval.

Whenever I get opportunity I speak in conferences, user groups, colleges. In these 6 years I have delivered around 50 sessions.

image

In these six years, I have been awarded as Microsoft MVP 4th times, C# Corner MVP 4th times and Telerik MVP 1 time.

 

image

would take this opportunity to thank each one of you for your support in my journey. In coming years I will focus on Cloud, Node.js, JavaScript and other technologies.

== and === operators of JavaScript in simple words

There are astronomical articles and blog posts have been written on == and === operators in JavaScript but I had tough time understanding it. So I decided to write my learning in this blog post. I will try to explain == and === in simplest words.

To start with try to understand difference between these two in below image,

image

=== is known as identical operator and it checks whether two operands are identical or not whereas == is known as equality operator and it checks whether two operands are equal or not. Now let us try to understand difference between identical and equal in context of JavaScript.

Identical operator or === will first evaluates the operands and perform operation on evaluated value.

Null and undefined are equal not identical

In JavaScript null and undefined are equal not identical. In below code I am comparing null and undefined using == and === operator.


if (null === undefined) {
 console.log("null and undefined is identical ");
}
else {
 console.log("null and undefined is not identical");
}

if (null == undefined) {
 console.log("null and undefined is equal ");
}
else {
 console.log("null and undefined is not equal");
}

You will notice as output that === operator will return false whereas == operator will return true while comparing null and undefined.

Two values of different types are neither identical nor equal

In JavaScript two values of different types are neither equal == nor identical ===


var foo1 = "India";
var foo2 = 12345;
if (foo1 === foo2) {
 console.log("foo1 and foo2 is identical ");
}
else {
 console.log("foo1 and foo2 is not identical");
}

if (foo1 == foo2) {
 console.log("foo1 and foo2 is equal ");
}
else {
 console.log("foo1 and foo2 is not equal");
}

 

You will notice as output both == and === are returning false. One interesting fact about == is that first it tries to convert string to integer and then it does comparison. So if consider below example, foo1 is string with value 1 and foo2 is number with value 1.


var foo1 = "1";
var foo2 = 1;
if (foo1 === foo2) {
 console.log("foo1 and foo2 is identical ");
}
else {
 console.log("foo1 and foo2 is not identical");
}

if (foo1 == foo2) {
 console.log("foo1 and foo2 is equal ");
}
else {
 console.log("foo1 and foo2 is not equal");
}

 

== operator will return true on comparing foo1 and foo2 because it first type converts operands and then do the comparison.

If any value or both are NaN

If either value is NaN or both are NaN then neither they are identical nor equal. Consider below example,


var foo1 = NaN;
var foo2 = NaN;
if (foo1 === foo2) {
 console.log("foo1 and foo2 is identical ");
}
else {
 console.log("foo1 and foo2 is not identical");
}

if (foo1 == foo2) {
 console.log("foo1 and foo2 is equal ");
}
else {
 console.log("foo1 and foo2 is not equal");
}

== And === both operators will return false. Because NaN is neither equal nor identical to any other value including itself.

Boolean true and false are equal and identical to each other

If operand values are getting evaluated to Boolean true or false then they are identical and equal to each other.


var foo1 = true;
var foo2 = true;
if (foo1 === foo2) {
 console.log("foo1 and foo2 is identical ");
}
else {
 console.log("foo1 and foo2 is not identical");
}

if (foo1 == foo2) {
 console.log("foo1 and foo2 is equal ");
}
else {
 console.log("foo1 and foo2 is not equal");
}

== And === operators will return true since values of foo1 and foo2 are true. So Boolean true is identical and equal to Boolean true and Boolean false is equal and identical to Boolean false.

Two strings with same values are identical and equal. Two strings with different content and length are neither equal nor identical.

Two operands represent value of same object then they are equal and identical. If they represent different object then they are not identical but they could be equal. So in other words for operands of different object type === operator will always return false whereas == may return true.

Let us try to understand equality operator == and strict equality operator or identical operator as below,

image

We have seen in above examples that

  • Null and undefined are not identical but equal and == returns true on comparison
  • If one operand is number and other is string then string gets converted to number and then == compare them.
  • If one operand is object and other is primitive value like string or number then == first converts object in primitive values using toString or valueOf and then do comparison

I hope in this post you got some ideas about working with == and === operators in JavaScript. Thanks for reading.