Intro

Get going with Express JS

ExpressJS is a web server for NodeJS.

Port numbers

When starting a ExpressJS server it binds a process to a port number on the server it’s started on. Port numbers allow one to start multiple ExpressJS server instances on the same server, each one with it’s own port number.

This example starts a server instance on port 3000:

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

//start the server
var server = app.listen(3000);

This server instance is not useful, as it expose no routes.

Routes

Routes can be accessed using the HTTP protocol. ExpressJS support all the HTTP request verbs. We will focus on POST and GET requests.

To add a hello route to the server add the code below before the app.listen method call.

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

Our server instance now has a /hello HTTP GET route.

Setup and run a ExpressJS server instance

Follow these steps to setup a ExpressJS server instance

Read more details about installing ExpressJS here.

Basic Express server instance

Now create a file called server.js and copy the code below into it:

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

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

//start the server
var server = app.listen(3000, function () {

 var host = server.address().address;
 var port = server.address().port;

 console.log('Example app listening at http://%s:%s', host, port);

});

Now try this: