Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications.

Hello Word Code :

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

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

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

app.listen(8080);
console.log("http://localhost:8080");

Explanation :

var express = require('express'),

In this we created a variable and tell that we require express for this program.

app = express();

Here we created the instance of an app. Now we have to register the handler for our route for that we do

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

Here app.get method tells how to handle the get request for the particular url. In this we tell that all the request with “/” are handled by callback function which is function(req, res).

res.send("Hello World n");

This line send request and print hello world on browser.

app.listen(8080);
console.log("http://localhost:8080");

app.listen will listen the app at port 8080. So when we run our app and type http://localhost:8080 on browser it will print hello world.

One problem is that when we print like http://localhost:8080/abc, instead of giving 404 error it will print “Cannot get /abc”. In order to get 404 error we add this code. Here “*” means handle everything.

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

 

Advertisements