How to quickly get started building web app with Express JS

How to quickly get started building web app with Express JS

Learn back-end web development in the 30-days challenge

Introduction

NodeJS provides HTTP modules we can use to create a basic web server. Whenever a user sends a request for a resource on the server, the server sends a response to the client

However, building web applications extend beyond the basic request-response cycle. Users perform multiple requests to the server for resources. For instance, request for an image, request for specified data from the database, request for different pages, sending data to the server, etc

In effect, you will send different requests to different routes, and on the server side there will be multiple functions to handle each request.

Node has its disadvantages. If you need to handle HTTP verbs differently (e.g. GET, POST, DELETE, etc.), separately handle requests from different routes, serve static files, or use templates to dynamically construct responses. You will have to spend valuable time writing all this code yourself.

To avoid this, it is productive to use a web framework like Express.

In this post, we answer the question, "What is Express?", and provide insights into what makes the Express web framework unique. By the end of this post, you should know the main features and the important building blocks of an Express application.

Understanding Web frameworks

When web development was in its infancy, all applications were hand-coded, and only the developer of a certain app could change or deploy it. Web frameworks introduced an effective way out of this trap.

A web framework is a software tool that supplies a way to build and run web applications. In effect, you avoid writing your own code and avoid wasting time scrutinizing for likely bugs.

What is ExpressJS?

Express is a node js web application framework that provides broad features for building web and mobile applications. It is used to build a single page, multipage, and hybrid web application.

Building a backend from scratch for an application in Node.js can be tiresome and time-consuming. Valuable time can be spent on setting up ports, route handlers, and writing every single code for each request.

The use of web frameworks such as Express.js can save developers time as most code has been written for developers to work with, allowing them to focus on other important tasks such as the business logic

Opinionated vrs Unopinionated frameworks

Web frameworks can be categorized as opinionated or unopinionated.

Opinionated frameworks have opinions about the "right way" to handle a particular task. It allows you to do something one way or makes other ways very difficult. Its authors have opinions on how you should write your code

If a framework is flexible and allows you to do things in whatever way you wish then it is "unopinionated". Unopinionated frameworks have far fewer restrictions on the best approach to glue components together to achieve a goal, or even what components should be used.

Why Express is an unopinionated framework

Express is unopinionated, meaning it permits developers the freedom to structure their code how they choose. You can insert any compatible middleware into the request handling chain, in any order you like. The app can be structured in one file or multiple files and using any directory structure.

The need for ExpressJS

In a typical data-driven website, a request is sent from the web browser to the web server for a resource. On receiving the request, the server works out the required action based on the information contained in the POST data or GET data and the URL route. The server chooses the corresponding route handler and assigns further action to it for that request. Writing a route handler from scratch can be a bit overbearing in Node

Depending on the requirement, it may read data or add data to the database. Subsequently, the server returns a response to the web browser, usually by dynamically creating an HTML page and inserting the retrieved data into the placeholders in an HTML template.

Features of Express

Express provides web developers with these features:

Route Handling

Express provides methods to specify what function is executed for a particular HTTP verb (GET, POST, DELETE, etc) and the URL route.

For instance in the code snippet below, all GET requests made to the route /, will be handled with a function that responds to the client with Hello World

(Don't worry if you don't understand the below, we come back to it later)

const express = require('express');
const app = express();
const port = 5000;

app.get('/', (req, res) => res.send('Hello World!'));

app.listen(port, () => console.log(`App is listening on http://localhost:${port}`));

Template Engines

Express also has methods to specify what template engine to use, where the template files are located, and what template to use to render a response.

Template engines permit developers to use static template files in their applications. At runtime, the template engine replaces variables in a template file with actual values and transforms the template into an HTML file sent to the server. This approach makes it easier to design an HTML page

Using Middleware

Everything from serving static files to handling errors to compressing HTTP responses is handled by middleware in Express apps.

Whereas route functions end the HTTP request-response cycle by returning some response to the HTTP client, middleware functions typically perform some operation on the request or response and then call the next function in the "stack", which might be more middleware or a route handler. The order in which middleware is called is up to the app developer.

Each time an express app receives a request, it needs to respond to the request. Middleware is a function that runs between the request and response cycle, and it is used to manipulate the request or response and then call the next function in the "stack", which might be more middleware or a route handler.

In a middleware stack, the initial middleware always runs first. Middleware functions can perform the following tasks in our application

  • Execute any code.

  • Make changes to the request and the response objects.

  • End the request-response cycle.

  • Call the next middleware in the stack.

The snippet below is an example of a middleware function called isLogged. This function prints Logged when a request to the app goes through it.

const isLogged = function (req, res, next) {
  console.log('Logged')
  next()
}

To implement the middleware function, use the method app.use and specify the middleware function.

The code below loads the isLogged middleware function before the route to the root path(/)

const express = require('express')
const app = express()

const isLogged= function (req, res, next) {
  console.log('logged')
  next()
}

app.use(isLogged)

app.get('/', (req, res) => {
  res.send('Hello World!')
})

Every time the app receives a request, it prints the message “Logged” to the terminal.

It is important to know the order in which middleware functions are loaded and executed: functions that are loaded first are also executed first.

If isLogged is loaded after the route to the root path, the request never reaches it and the app doesn’t print “Logged”, because the route handler of the root path terminates the request-response cycle.

Serving Static files

Express provides the express.static middleware to serve static files, which includes images, CSS, and JavaScript.

For instance, you can use the line below to serve images, CSS files, and JavaScript files from a directory named 'public' .

app.use(express.static("public"));

Using databases

Developers can use any database mechanism supported by Node. Among the options are PostgreSQL, MySQL, Redis, SQLite, MongoDB, etc.

To use these, you first install the database driver using npm. For instance, to install the driver for the widespread NoSQL MongoDB you would use the command:

npm install mongodb

The database can be installed locally or on a cloud server. In your Express code you require the driver, connect to the database, and then perform create, read, update, and delete (CRUD) operations on your app.

Summary

Congrats, on taking the time to read my post. You should now understand what a web framework is, what is Express, and why Express is referred to as an unopinionated framework.

You should also know some common features of an Express app like routing, template engines, middleware, and database.

In our next article, we will focus on setting up an Express server.

This article is the day 3 post on the 30-day challenge I am undertaking to learn backend development. Please feel free, to drop some insights, comment, or share the post to your networks