How to get started with Express.js? Express.js Full Tutorial

How to get started with Express.js? Express.js Full Tutorial

Express.js is a renowned JavaScript runtime published as open-source software on May 27, 2009, by Ryan Dahl. Its primary usage is to create server-side Web Applications and APIs.

Today, Node.js is used to build the majority of server-side web applications. Even front-end developers may effortlessly adopt Node.js. Because Node.js is essentially JavaScript running on the server, developers can use their current JavaScript skills to create server-side apps.

Although Node.js includes support for most of the features required to construct a robust API, having a framework simplifies our lives.

This article will discuss Express.js and why it became popular among developers.

A simple API using the built-in HTTP module

Let’s try to make a simple API with the built-in HTTP module that Node.js provides.

const http = require('http');

const port = process.env.PUBLIC_PORT;

const server = http.createServer((req, res) => {
  if (req.url === '/') {
    res.statusCode = 200;
    res.setHeader('Content-Type', 'text/plain');
    res.end('Hello from codedamn!');
  } else if (req.url === '/test') {
    res.statusCode = 200;
    res.setHeader('Content-Type', 'text/plain');
    res.end('Test endpoint!');
  }
});

server.listen(port, () => {
  console.log(`Server running at <http://localhost>:${port}/`);
});Code language: JavaScript (javascript)
Response from the server for / route
Response from the server for / route
Response from the server for /test route
Response from the server for /test route

Our two endpoints are working correctly, but did you notice how much redundant code we have written? Imagine having 20 endpoints. It’ll be a mess. Furthermore, if we want to nest specific endpoints, we’ll end up with nested if-else statements, which affect code readability and maintainability.

What is Express.js?

Express is a lightweight and versatile Node.js web application framework that provides various features for mobile and web apps.

We can quickly build server-side web apps and APIs with Express.js. Even front-end devs who know JavaScript but have no expertise with the back-end may learn and create APIs with Node.js and Express.js.

Let’s now learn how to create a simple Todos API with Node.js + Express.js.

Installation and Setup

To install Express.js on a project, we will use the following commands,

# Initialize NPM
npm init -y

# Install Express.js
npm install expressCode language: Bash (bash)

To verify the installation, we check if there is a package.json file created and if express gets listed as a dependency.

The package.json file
The package.json file

After installation, create an index.js file at the root of the project. This file is the entry point of our Express.js application. We first create an app instance using the express function. Furthermore, we define a port and will start listening to it using the app.listen() method.

const express = require('express');

const app = express();

const port = 1337;

app.listen(port, () => {
    console.log('server running');
});Code language: JavaScript (javascript)

On running our file using node index.js, we see a console message ‘server running.’

Express server running
Express server running

It means that we have successfully created an Express.js server. We can’t see anything on navigating to the URL because we haven’t set up any endpoints yet.

Routing

Routing is the technique by which a web server replies to a client request to a certain endpoint. The endpoint comprises a URI (a path like / or /todos) and an HTTP method like GET, POST, PUT, DELETE, etc.

To define a route in Express.js, we write,

app.METHOD(PATH, HANDLER);Code language: JavaScript (javascript)

The METHOD is a valid HTTP request method, and PATH is the path to our endpoint (like / or /todos). HANDLER is a callback function that runs whenever a request to that endpoint is received.

Routing parameters

Route parameters store the value of URL segments at the position where they appear. Since the URL contains parameters, we use the request.params object to access them.

app.get('/todos/:id', (request, response) => {
    // do something
})Code language: JavaScript (javascript)

On making a GET request at /todos/123, the request.params.id will correspond to ‘123’.

Request and Response

The client submits a request to a server, and the server responds to the client. A request and a response object are supplied as arguments whenever the callback function (or route handler function) associated with an endpoint gets invoked.

This request object contains all the data about the request, like the path, the headers, the request payload, etc. On the other hand, the response object has methods to modify and send the response back to the respective client.

HTTP methods recap

There are five basic HTTP methods accessible. Let’s take a look at them one by one.

GET

The GET method requests some information from the server.

app.get(PATH, (request, response) => {
    // send information
})Code language: JavaScript (javascript)

POST

The POST method sends information to the server, which causes a change in the server’s state.

app.post(PATH, (request, response) => {
    // add information
})Code language: JavaScript (javascript)

PUT

The PUT method replaces previously existing information on the server with updated information.

app.put(PATH, (request, response) => {
    // update information
})Code language: JavaScript (javascript)

PATCH

The PATCH method makes partial changes to existing information on the server.

app.patch(PATH, (request, response) => {
    // patch information
})Code language: JavaScript (javascript)

DELETE

The DELETE method deletes some specified information from the server.

app.delete(PATH, (request, response) => {
    // delete information
})Code language: JavaScript (javascript)

Setting up an endpoint

As we have already seen, creating an endpoint is a simple task. Let’s create a basic endpoint that responds with the text ‘Hello from Codedamn.’

app.get('/hi', (request, response) => {
    response.send('Hello from Codedam');
})Code language: JavaScript (javascript)

Let’s break down the code piece by piece.

get
It is the HTTP request method.

/hi
The string hi represents the path to our endpoint.

(req, res) => { ... }
It is the request handler. It’s a callback function that gets called whenever the client makes a GET request to /hi.

On navigating to the endpoint, we get the response “Hello from Codedam.”

Response from the server for /hi route
Response from the server for /hi route

NOTE: If using Codedamn Playgrounds, open the preview in a separate browser tab.

Middlewares

Middleware functions have access to the request object, the response object, and the next function in an application’s request-response cycle. These functions modify request and response objects to do tasks such as processing request bodies, adding response headers, modifying the request-response cycle further, ending the request-response cycle, and calling the next middleware function.

There can be multiple middlewares in our Express.js application. The first middleware calls the next middleware using the next() function. Middlewares run in the order they are declared in the code.

We will use the app.use() method to create a middleware. The app.use() method takes a callback function, i.e., the middleware function, as an argument. The callback function receives a request object, a response object, and a next function.

To better understand things, let’s create a custom middleware.

app.use((request, response, next) => {
    console.log(request.method, request.url)
})Code language: JavaScript (javascript)

The middleware function logs the request method and the API endpoint and then calls the next() function. The next() function call will run the request handler callback function for the respective endpoint.

Custom middleware
Custom middleware

Quick Tip

You can supply an optional path argument to the app.use() method. It ensures that the middleware function runs only when a request for the provided path is received.

app.use('/hi', (request, response, next) => {
    console.log(request.method, request.url)
})Code language: JavaScript (javascript)

Third-Party Middlewares

Middlewares are quite helpful since you can preprocess both requests and responses. Although we may write our custom middleware, starting from scratch with everything is not a good idea. We can utilize third-party middleware to fulfill our objectives. Although Express.js includes several third-party middleware, we may add more using the NPM package manager based on our needs and use cases.

Let’s discuss some of the most frequently third-party middleware.

express.json()

The express.json() is a built-in middleware in Express.js. Its primary purpose is to parse a request with JSON payloads. It attaches the parsed payload to the request object. We can access it using request.body.

app.use(express.json());Code language: JavaScript (javascript)

express.static()

The express.static() function is a built-in middleware function in Express. It serves static files and assets, such as CSS and JavaScript files, images, etc., to the client.

app.use(express.static(path.join(__dirname, 'public')));Code language: JavaScript (javascript)

Mini Project

Let’s create a Todos API project, as promised. We shall go step by step to ensure that everything is clear.

Installing Express.js

We start by installing Express.js using NPM.

# Initialize NPM
npm init -y

# Install Express.js
npm install expressCode language: Bash (bash)

A package.json file with express listed as a dependency will be get created.

Setting up the endpoints

We will have three endpoints for this project:

  1. GET /todos – To fetch the list of all todos.
  2. POST /todos – To add a new todo.
  3. DELETE /todos/:id – To delete an existing todo.

To handle the list of todos, we will define a global variable containing the list of todos. Let us now create the API endpoints.

const express = require('express');

const app = express();

const port = 1337;

let todos = [];

// GET /todos
app.get('/todos', (request, response) => {
    response.json(todos);
})

// POST /todos
app.post('/todos', (request, response) => {
    // get the todo from the request body
    const todo = request.body;

    // add the todo to the list
    todos.push(todo);

    // send success response
    response.send('Todo added successfully!');
})

// DELETE /todos
app.delete('/todos/:id', (request, response) => {
    // get the todo id
    const id = request.params.id;

    // delete the todo
    todos = todos.filter((todo) => todo.id !== id);

    // send success response
    response.send('Todo deleted successfully!');
})

app.listen(port, () => {
    console.log('server running');
});Code language: JavaScript (javascript)

Setting up the middlewares

To add a new to-do item, the user will make a POST request with a request body containing the to-do item in JSON format. We will use Express’s built-in express.json() middleware to parse the JSON.

app.use(express.json());Code language: JavaScript (javascript)

Testing the API

To test the API, we will use Postman. If you don’t know about Postman, it is an API platform for building and testing APIs. To learn more about Postman, you can visit their official website.

Let’s see if our API is functioning correctly. We will test each endpoint individually. Since we won’t have any to do on our list, we start by adding some using the POST route.

POST /todos

We will make a POST request to /todos with the following payload.

{
    "id": "1",
    "todo": "Complete assignment"
}Code language: JSON / JSON with Comments (json)
POST endpoint functioning correctly
POST endpoint functioning correctly

We’re receiving the correct response, which means the todo is successfully added to our list of todos; let’s add a couple more.

{
    "id": "2",
    "todo": "Watch the recent Codedamn video"
}
{
    "id": "3",
    "todo": "Watch JavaScript course lecture"
}Code language: JSON / JSON with Comments (json)

GET /todos

GET endpoint functioning correctly
GET endpoint functioning correctly

We receive all the todos we recently added when we send a GET request to the /todos endpoint. It indicates that the endpoint is operating correctly.

DELETE /todos

To delete a todo, we need to send the ID of the particular todo. We provide the ID of the todo using the route parameter. To delete a to-do with an ID of 3, we will send a DELETE request to /todos/3.

Let’s delete the todo with an ID of 3.

DELETE endpoint functioning correctly
DELETE endpoint functioning correctly

We get the correct response, which means we have successfully deleted the todo with an ID of 3 from the list. We can verify by again fetching the list of todos by making a GET request to /todos.

Todo was deleted from the list.
Todo was deleted from the list.

That’s it! We have created a basic Todos API with Node.js and Express.js ?

Conclusion

In this article, we discussed what Express.js is and why it is so popular. We constructed a server with Express.js and the built-in HTTP module and discovered how simple it is to build a server with Express.js. Moreover, we learned some essential back-end concepts such as routing, route parameters, HTTP methods, etc., and how to create a server with Express.js. Additionally, we implemented a Todos API using Express.js, using all the concepts we learned. Finally, we tested our API using Postman.

You can access all the source code using the following link:
https://codedamn.com/playground/Y-VcNUMtrSch1eaapaHcm

Thank you so much for reading ?

Sharing is caring

Did you like what Varun Tiwari wrote? Thank them for their work by sharing it on social media.

0/10000

No comments so far

Curious about this topic? Continue your journey with these coding courses: