A comprehensive introduction to Express JS

A comprehensive introduction to Express JS

Introduction

Node.js, a javascript runtime based on Chrome’s V8 JavaScript engine, is revolutionary in its own right. Node.js enables developers to use Javascript, which typically runs on a browser, to write server-side code. For Javascript developers, in particular, this is heaven-sent as they can now work on the backend without learning a new programming language.

However, working with Node.js itself can be a bit of a hard nut to crack, particularly for new developers. Tasks like creating servers, listening for requests, parsing request bodies and sending back a response require writing complex server-side logic. This can get overwhelming, particularly for beginners. This is where Express comes in to save the day.

This article is the first part of a series of articles providing a detailed comprehensive introduction to using Express. This article covers how to set up your Express project and its package.json file. Additionally, it covers npm scripts and how to install and use Nodemon and Express. Finally, the article covers how to use Express to create a node server that listens for requests and sends back a response.

Prerequisites

  • Fundamental knowledge of HTML, CSS and JavaScript
  • Fundamental knowledge in Node.js is desirable but not a must-have
  • A code editor and a browser. This article will use VS Code and Chrome respectively.
  • Node.js and Node Package Manager(NPM) Installed on your machine
  • An internet connection

What is Express?

From its official documentation, Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications. Additionally, its HTTP utility methods and middleware can be used in creating robust Application Programming Interfaces (API) quickly and easily.

A framework is reusable code written by other people that you use to structure your programs. A framework provides ready-made components or solutions we can use to speed up development

An API is a software intermediary that allows programs to communicate with each other without user intervention

As a framework, Express provides you with tools you can use to perform the following tasks:

  • Create servers and listen for requests
  • Parse incoming requests
  • Match incoming requests with appropriate routes
  • Send back a response

Why use Express?

The following are some of the reasons to use Express:

  • It provides reusable built-in components which allow you to build a node application faster
  • It allows you to focus on the unique business logic of your application instead of complex server-side logic
  • It is flexible and pluggable allowing you to add other modules to help in your development

Getting started

A general rule while building Node.js applications is to have a package.json file which is stored in the root directory of a project.

The package.json file will store metadata such as the name of the project, its description and its author. Importantly though, it will store metadata on the packages and dependencies needed to run the project. NPM uses the package.json file to start your project, run scripts, install dependencies and publish a project on npm’s registry.

dependencies are the external code or packages that a project requires for it to run. There are two types of dependencies in a package.json:

  • dependencies: packages required by a project in production
  • devDependencies: Packages that are only needed for local development and testing

Additionally, for you to install any packages in your project, such as Express in this case, or to make your project publicly available, you need a package.json file.

Therefore the first step in creating an express project will be creating a package.json file for the project.

To create a package.json file for the project:

  1. Open a terminal window and create a folder called ExpressProject by typing mkdir ExpressProject. You can, however, give the folder any name you like.
  2. Navigate into the folder by typing cd ExpressProject
  3. Create a package.json file by typing npm init. This opens a utility that walks you through creating a package.json file.

This utility will provide a guide to creating a package.json file. The utility will show prompts where you can type in the information to be stored in the package.json file. You can also press enter without typing any value for a given field to use the suggested value, provided in parentheses, or leave it blank.

The package.json file can be edited later in the code editor. Do not panic if you make typing errors

The following are prompts that will show up and what to do once they show up:

  1. package name: (expressproject) - press enter

    the package name depends on the name you gave your folder

  2. version: (1.0.0) - press enter
  3. description - Type a short description of what your project does and press enter once done
    description: A Node.js application using Express
  4. test command:press enter
  5. git repository: press enter

    If you have a git repository, paste a link to the repository. However, to keep this tutorial beginner friendly, no git repository is required

  6. keywords: press enter
  7. author: provide the name of the author of the project and press enter.
  8. license: (ISC) press enter
  9. Is this OK? (yes) This is accompanied with a preview of the package.json file that is going to be created is provided. press enter

    If you notice an error in the package.json file, it is still okay to press enter as you can edit the package.json file in the editor.

  10. Type code . to open the folder in Vs Code

Once done you should have such a package.json file created in your project folder.

vsCodeOne.jpg

Installing packages needed for the project

This project will require installing two packages namely Nodemon and Express. The packages installed will be saved in a folder called node_modules which will be created automatically once a package is installed.

Installing Nodemon

Nodemon is a tool that automatically restarts a node application when file changes are detected in the application's directory. This is handy as you won't need to manually restart a Node Server every time you make changes to a file.

You can skip this step if you already have Nodemon installed.

To install nodemon

  1. Enter npm install -g nodemon in the terminal

    the -g flag is used to install Nodemon globally in your system. This way, you can use Nodemon anywhere on your computer and not just in your current project directory.

In case of permission errors if you're using a linux sytem, use sudo npm install -g nodemon and press enter

Installing Express

To install express:

  1. Enter npm install express in the terminal

After installing Nodemon and Express in your project, open your package.json file.

{
  "name": "expressproject",
  "version": "1.0.0",
  "description": "A Node.js application using Express",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "Collins Kariuki",
  "license": "ISC",
  "dependencies": {
    "express": "^4.18.2",
    "nodemon": "^2.0.20"
  }
}

Notice a new field called dependencies has been added to the package.json file. This field has values showing the dependencies needed for our project, in this case, Express and Nodemon together with the versions used in the project.

When you receive a Node project with a package.json file, running npm install in the project directory will install all the needed dependencies for the project.

Another section of interest in the package.json file is "main": "index.js". This shows the entry point to your application. When you run your node application, Node will use the indicated main file, in this case, index.js to start your application.

Therefore when creating your application, you need to create a file called index.js which will act as the entry point to your application. However, you can give the file a different name. When you do this, make sure to make the change in the package.json file to reflect the change in the main file.

Edit "main": "index.js"to"main": "app.js". You can give your main file any name you like. This article will useapp.js` as the main entry point to the application.

In the package.json file script is another important section. Script allows you to write your own npm scripts with you can run using npm run <script-name>

npm scripts are common shell commands stored in the script section of a package.json file to automate repetitive tasks such as running your node application

Typically, you run node applications using by entering Node <name of application file> in the terminal. For instance, if your node application is stored in a file called app.js, you run the application by entering node app.js in the terminal opened at the folder containing the app.js file.

However, since you installed Nodemon to restart your server anytime changes are made in the file, use Nodemon to run your node application.

To run a node application using Nodemon enter nodemon <name of application> in the terminal. For instance, to run a node application in a file called app.js use nodemon app.js

To make running your app even easier, use npm scripts. In your package.json file, edit the script section by adding the line "start": "nodemon app.js". The script section of your package.json file should now look like this:

{
  "name": "expressproject",
  "version": "1.0.0",
  "description": "A Node.js application using Express",
  "main": "app.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "nodemon app.js"
  },
  "author": "Collins Kariuki",
  "license": "ISC",
  "dependencies": {
    "express": "^4.18.2",
    "nodemon": "^2.0.20"
  }
}

The script we have added is called start, therefore, to run it, typically you'd run npm run start in the terminal. This will start your node application once you add server-side logic to it.

However, with npm, there are special script names associated with common tasks when creating a node application. These scripts have aliases, such that you don't need to write the command run to execute them in a terminal. You can simply run their alias. These script aliases are:

  • npm start alias for npm run start
  • npm stop alias for npm run stop
  • npm test alias for npm run test
  • npm restart alias for npm run restart

Therefore, to start a node application, you can simply execute npm start instead of npm run start. However, both commands work but the former saves you a few characters. Likewise, to restart a node application, you can simply execute npm restart instead of npm run restart. However, for other scripts without aliases, you need to execute npm run <script name>

To start node applications, this article will use npm start. Once you run this command, Node.js will look in your package.json file and execute the command associated with the script. In this case, Node.js will execute nodemon app.js

Creating a server using Express

To create a server using Express, follow the following steps:

  1. Create a new file in the project folder and name it app.js. Open it in the code editor

    the file is named app.js because, in the package.json file, the entry point of the Node application was set to "main": "app.js". If your main section in the package.json is set to a different javascript file name such as index.js name your file index.js

  2. Import Express into your app.js file and save it to a constant. To use Express in your file you first need to import it into your file using require() and save it to a constant. Enter the following line to import Express
    const express = require('express');
    

    You can give your constant any name you like, but it is good practice to give the constant the name of the package you are importing, in this case, express. You can also use a variable instead of a constant, but constants are generally preferred because you don't want any changes made to them.

  3. Create an express application and store it in a constant by running express as a function
    const app = express();
    

    The line above initialises an Express object which will store Express methods in the constant named app. This constant will be used to access Express methods and functionality.

  4. Create a middleware that will be executed for every incoming request and sends back a response

    app.use((req,res,next) => {
     res.send('<h1>Hello from an Express server</h1>')
    })
    

    In the code above, the function use() allows you to add express middleware functions. A middleware function is a function that has access to the request object(req), the response object(res) and the next function in the application request-response cycle. The code above has one middleware function to handle requests and responses, the middleware function is

    (req,res,next) => {
     res.send('<h1>Hello from an Express server</h1>')
    

    The argument req represents the request object, res is the response object and next is a function that if called, executes the next middleware in line. Whereas you can give these arguments any name you like, their order matters. The first argument will always be the request object, the second the response object and next the final argument. This middleware function will be executed every time a request is made. In the middleware function the line

    res.send('<h1>Hello from an Express server</h1>')
    

    is used to send back a response once a request is made. To send a response, you use the res object which is an argument in the middleware function. The response object, res has a function called send() that is invoked to send the actual response which in this case is a simple h1 element wrapped in quotes.

  5. Set the server to listen for requests at port 3000

    app.listen(3000);
    
  6. Start your node application by executing the following command in the terminal
    npm start
    
    If successful your code editor should display something similar to this: server.png
  7. Go to your browser and enter http://localhost:3000

Entering the localhost:3000 sends a request to your running node server, listening for requests at port 3000. Your running server in turn sends a response and you should see such a screen showing the response sent from your node server expressServer.png

Next Steps

After successfully setting up a node server using Express, the next step is to dive into express middleware which is discussed in the next article which is a follow to this article.