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.

var express = require('express'),
app = express();

app.get('/', function(req, res) {
    res.send("Hello World!");
});

app.get('*', function(req, res) {
    res.send("Page no found", 404);
});

app.listen(8080);
console.log("Server listening on port 8080");

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

npm install express

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.

var express = require('express'),
app = express();

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

app.get('/', function(req, res) {
    res.send("Hello World!");
});

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 ‘*’.

app.get('*', function(req, res) {
    res.send("Page no found", 404);
});

‘*’  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

node app.js

We will get the  log message

Server listening on port 8080

Now in our Browser. If we type URL

http://localhost:8080/

We will get following out put in browser.

Hello World!

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

http://localhost:8080/page

We will get message from ‘*’ handler as

Page not found

So this a basic Hello World program using express framework.