How to get started with Express.js

Introduction

In this tutorial we will learn how to setup a Node.js server using the Express.js framework.

You can install Express.js with the following NPM command:

npm install express --save

In the first section below we will setup a very simple “Hello World” app and in the second section we will learn how to configure routes to listen to different HTTP methods (GET, POST, PUT and DELETE).

Hello world with Express.js

We will start our code by importing the express.js module we have just installed. Note that this module exports the express function, which we will use below.

const express = require('express')

After this, we will create an Application object by calling the express function we have just imported.

const application = express();

Then, we will register a route for our HTTP web server which will listen to GET requests. We do this with a call to the get method on our Application object.

This method receives as first input a string with the path for this server route. We will use the index path, which corresponds to “/“.

As second input, the get method receives a callback function that will be executed every time a request is made to this route. It’s up for us to define what we will do inside this callback function, but a common flow is doing some procedure (ex: getting information from the database) and returning an answer back to the client.

When invoked by the framework, this callback function receives two parameters:

  • A Request object, which represents the HTTP request and contains properties of the request. We won’t use it on this first example;
  • A Response object that represents the HTTP response from the Express.js application.

To make our code more compact, we are going to use an anonymous function as callback (you can read more about anonymous functions here),.

application.get('/', function(req, res){
  // Implementation of the callback function
});

The implementation of the callback will be very simple, as we will only return back a “Hello World” message to the client. For this, we simply need to call the send method on the Response object. As input, we pass the response body in one of the following formats: a Buffer object, a string, an object, a Boolean or an Array [1]. In our case, we will pass a string.

res.send('Hello World from Express.js')

The full code for registering the route can be seen below.

application.get('/', function(req, res){
  res.send('Hello World from Express.js')
});

To finalize, we will call the listen method on our Application object, for our server to start listening to incoming requests.

As first input we pass the port where the server will be listening. I’ll be using port 8080. As second input we can optionally pass a callback function that will be invoked when the initialization of the app is finished. Like before, we will be using an anonymous function for this callback. In our example, its implementation will simply consist on printing a message to the console indicating that the application is initialized.

application.listen(8080, function(){
  console.log("Application initialized.");
});

The complete code can be seen below.

const express = require('express');

const application = express();

application.get('/', function(req, res){
  res.send('Hello World from Express.js')
});

application.listen(8080, function(){
  console.log("Application initialized.");
});

To test the code, simply run it on a tool of your choice. In my case, I’m using Visual Studio Code with the Code Runner extension.

Upon running, you should get a message similar to figure 1 printed to the console, indicating that the application was initialized.

Output of the callback function executed after the initialization of the Express.js application.
Figure 1 – Output of the callback function executed after the initialization of the Express.js application.

After that, open a web browser of your choice and access the following URL:

http://localhost:8080/

You should get the “Hello World” message illustrated in figure 2, like we defined in our code.

Express.js "Hello World".
Figure 2 – Express.js “Hello World”.

Routes answering to other HTTP method

In this section we will check how to set routes to listen to other HTTP methods. Most of the code will be similar, so we will focus on the registering of the routes.

Like we have seen before, to setup a route to answer to HTTP GET requests, we simply need to call the get method on the Application object, passing as first input the route and as second the handling function.

application.get('/', function(req, res){
  res.send('GET')
});

For registering a route to listen to POST requests we have the post method. The parameters are exactly the same as before: a string with the server route and a callback function that will be executed upon receiving a request on that route. For illustration purposes, we will simply return a “POST” message, so when testing our client we can confirm that the correct callback was executed.

application.post('/', function(req, res){
  res.send('POST')
});

Similarly, we have the put and delete methods to register routes to listen to HTTP PUT and DELETE methods, respectively.

application.put('/', function(req, res){
  res.send('PUT')
});

application.delete('/', function(req, res){
  res.send('DELETE')
});

The complete code is shown on the snippet below.

const express = require('express');
const application = express();

application.get('/', function(req, res){
  res.send('GET')
});

application.post('/', function(req, res){
  res.send('POST')
});

application.put('/', function(req, res){
  res.send('PUT')
});

application.delete('/', function(req, res){
  res.send('DELETE')
});

application.listen(8080, function(){
    console.log("Application initialized.");
});

To test the additional methods we have added, we can use a tool such as the Postman client, which allows us to select the HTTP method and perform requests.

Figure 3 shows the result of doing a HTTP POST request to our index route and, as expected, we receive the “POST” string as response. If you test the 3 other methods we have used, you should get similar results.

Response to the POST request, performed using Postman.
Figure 3 – Response to the POST request, performed using Postman.

Suggested readings

References

[1] https://expressjs.com/en/api.html#res.send

Leave a Reply

%d bloggers like this: