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.

Create Image Server using WCF WEB HTTP Service

Last post I wrote on WCF Web HTTP Service: why and how. This post was for beginners in which I discussed how to get it started and write your fist WCF WEB HTTP Service. In this post we will go one step further and learn to work with streams or to be precisely images. Service will return image based on the input from client. We are going to create an image server. Image server will do following task

  • Read requested image from file system on server
  • Convert that to stream
  • Return stream to clients

We are going to create WCF WEB HTTP Service which will act as image server. So to start with let us create Service Contract.

 


using System.IO;
using System.ServiceModel;
using System.ServiceModel.Web;

namespace Demo1
{    
    [ServiceContract]
    public interface IService1
    {
        [OperationContract]
        [WebGet]
        Stream FetchImage(string imageName);      
       
    }
}


In above Service, there is one Operation Contract which returns a stream. Operation Contract can be accessed using baseurl/FetchImage?imageName={imagename with extension}. Client will pass image name in query parameter to fetch a particular image. If image is not present on image then null would be returned from service.

Service implementation is very simple. You need to do following steps to fetch image and return it as stream.

Step 1: First check for existence of the image. If it exists got to step 2 else go to step 4

Step 2: Read image as FileStream

Step 3: Set Outgoing Request Content Type as image/jpeg

Step 4: convert string Image does not exist as stream and return

Service is implemented as below,


public class Service1 : IService1
    {       

        public Stream FetchImage(string imageName)
        {
            string filePath = @"c:\\" + imageName;

            if (File.Exists(filePath))
            {
                FileStream fs = File.OpenRead(filePath);
                WebOperationContext.Current.OutgoingRequest.ContentType = "image/jpeg";
                return fs;
            }
            else
            {
                byte[] byteArray = Encoding.UTF8.GetBytes(" Requested Image does not exist :(");
                MemoryStream strm = new MemoryStream(byteArray);
                return strm;
            }
        }        
    }


Service implementation is very simple but one line of code in which we are explicitly saying that outgoing response content type is image/jpeg

image

Already we have covered this in previous post about EndPoint configuration but for quick reference open markup of .svc file and add use Factory method System.ServiceModel.Activation.WebServiceHostFactory to create WEB HTTP Service.

image

This is what all you need to do to create an Image Server as WCF WEB HTTP Service. You can test server from IE browser.

image

And if requested image is not present then error message will be rendered as below,

image

Now you can go ahead and consume and work with this image server in any kind of client able to perform HTTP GET operation. In further post we will get into details of consuming this service from various kind of clients. I hope this post will help you.

WCF Web HTTP Service: why and how

Very often I talk on WCF to user groups and find developers confused on various forms of WCF. For example some of the questions I get are as follows

  • How to create REST Service
  • Can we create REST and SOAP Service together
  • What is WCF Web HTTP Service
  • How Web HTTP Service and WCF REST Service are different to each other
  • Can I host HTTP Service and REST Service in a console application
  • Why we need REST and HTTP Services
  • What kind of security can be applied on REST and HTTP Services and many more questions of this kind

In this post I will answer few of the above questions regarding WCF Web HTTP Services.

By definition, WCF Web HTTP programming model allows services to be exposed on non-SOAP EndPoints and helps to create WEB HTTP Services. Now a question may arise that why we need HTTP Services and what are the advantages of using that.

Mainly HTTP Services are designed and created for wide range of clients. Any application capable of following can be potential clients

  • Understand HTTP protocols and verbs
  • Can process URI and URL Schemes
  • Can work with different types of message and data formats
  • Perform HTTP Get and HTTP Post operations

Web HTTP Services doesn’t work on SOAP message format however any serilizable type can be returned from Web HTTP Services. Since HTTP Service does not work with SOAP so all WCF Security features cannot be applied on this. However basic Transport level security can be applied to WCF Web HTTP Services.

Let us see how we can create a very basic WCF Web HTTP Service. Create WCF Service Application project from WCF tab to create Web HTTP Service

image

After creation of project we need to create Service Contract.


 [ServiceContract]
    public interface IService1
    {

        [OperationContract]
        [WebGet]
        string HelloGet(string   name);

        [OperationContract]
        [WebInvoke]
        string  HelloPost(string  name);
       
    }


Above I have created very basic service. Service contains only two methods. One method will work on HTTP GET and other will work on HTTP POST operation. There are restrictions on passing parameters in query string. For example string can be passed in query parameter.


public class Service1 : IService1
    {       

        public string HelloGet(string name)
        {
            return "Hello GET " + name; 
        }

        public string HelloPost(string name)
        {
            return "Hello POST" + name; 
        }
    }



Above Service Contract is implemented as below. It’s very simple implementation in which service is returning string with concatenating of input string parameters.

Now there are various ways WCF WEB HTTP Services can be hosted and its EndPoint can be configured. You can configure and host service

  • In IIS
  • In Windows Services Application
  • In Managed Application like Console Application
  • Windows Azure Services

In this post let us learn how EndPoint can be configured for Web Server hosting like IIS. It’s very simple to configure EndPoints for HTTP Services. You can use Factory method System.ServiceModel.Activation.WebServiceHostFactory to create WEB HTTP Service.

image

You can fetch service from browser by navigating to URL as below. Keep in mind that port number could be different in your scenario.

http://localhost:55400/Service1.svc/HelloGet?name=dj

You can notice that we are passing input dj as string in query parameter. Response from service will be as below,

image

Another way service can be configured and hosted in a console application. In Console Application first you need to add reference of System.ServiceModel and System.ServiceModel.Web in the project.


using System;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.ServiceModel.Web;
using Demo1;

namespace ConsoleAppHostingService
{
    class Program
    {
        static void Main(string[] args)
        {
            WebServiceHost host = new WebServiceHost(typeof(Service1), new Uri("http://localhost:8989/"));
            ServiceEndpoint endpoint = host.AddServiceEndpoint(typeof(IService1), new WebHttpBinding(), "");
            ServiceDebugBehavior sdb = host.Description.Behaviors.Find<ServiceDebugBehavior>();
            sdb.HttpHelpPageEnabled = false;
            host.Open();
            Console.WriteLine("Service is running");
            Console.WriteLine("Press enter to quit...");
            Console.ReadLine();
            host.Close();

        }
    }
}


Few points about above hosting code are as follows

  • WEB HTTP Service should be hosted in a WebServiceHost instance.
  • WebHttpBinding is used to created HTTP Service
  • Help page is disabled

On running Console Application, service can be accessed on URL passed in WebServiceHost instance

image

In this way you can create WCF WEB HTTP Service. In further posts we will learn how to consume this service in various kind of clients and work with different kind of data format. I hope this post will help you.