NodeJs and Express framework basics

NodeJs and Express framework  basics

We have already learned how to select data from MongoDb using Nodejs findOne. In this article we will create a baisc Hello World program using NodeJs and Express. Consider a following program below.

In our first line we need to include ‘express’ module. If express is not already installed then first need to install it.

This command will install express framework.

First of all we have to get reference to express module and then create an instance of our app.

Next thing we need to do is register handler for our routes

So we did app.get for ‘/’ and gave it a callback function when it is requested and gave it a request object and an object for response.

The app.get  method is a way to tell express that how to handle a particular. In this example we are telling express that all get requests to the resource ‘/’  meaning the url nothing after it should be handled by this function we are passing in. Note that callback takes two arguments, these are request and response objects and are passed to our callback by express so we can use them in our route handling code.

So in body of function we handle the request. s from the context we know that request is made for ‘/’ so any user who requests for ‘/’ we will only return a “Hello World” using res.send() method.

Next we register a route for ‘*’.

‘*’  basically means any route that was not handled by a previous handler will be handled by this handler. So we did here is that we send back “Page not found” with a 404 not found code.

Running the script:

Now save this code as app.js . and run  it on command line using

We will get the  log message

Now in our Browser. If we type URL

We will get following out put in browser.

Now if we request any page other then ‘/’ like

We will get message from ‘*’ handler as

So this a basic Hello World program using express framework.