In this section, we will cover how to set up an Express application from scratch. Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications.

Objectives

By the end of this section, you will be able to:

  • Install Express using npm.
  • Create a basic Express application.
  • Understand the structure of an Express application.
  • Run the Express application on a local server.

Prerequisites

Before you start, ensure you have Node.js and npm installed on your machine. If not, refer to the "Setting Up Node.js" section in Module 1.

Step-by-Step Guide

  1. Initialize a New Node.js Project

First, create a new directory for your project and navigate into it using the terminal:

mkdir my-express-app
cd my-express-app

Initialize a new Node.js project by running:

npm init -y

This command will create a package.json file with default settings.

  1. Install Express

Next, install Express as a dependency:

npm install express

  1. Create the Application File

Create a new file named app.js in the root of your project directory. This file will contain the code for your Express application.

  1. Write the Basic Express Application

Open app.js in your code editor and add the following code:

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

// Define a route handler for the default home page
app.get('/', (req, res) => {
  res.send('Hello, World!');
});

// Start the server
app.listen(port, () => {
  console.log(`Express app listening at http://localhost:${port}`);
});

  1. Run the Application

To run your Express application, use the following command in your terminal:

node app.js

You should see the following output:

Express app listening at http://localhost:3000

Open your web browser and navigate to http://localhost:3000. You should see the message "Hello, World!".

Understanding the Code

Importing Express

const express = require('express');

This line imports the Express module.

Creating an Express Application

const app = express();

This line creates an instance of an Express application.

Defining a Route

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

This code defines a route handler for the root URL (/). When a GET request is made to the root URL, the server responds with "Hello, World!".

Starting the Server

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

This line starts the server and listens on port 3000. When the server starts, it logs a message to the console.

Practical Exercise

Exercise 1: Add a New Route

  1. Add a new route to your Express application that responds with "About Us" when a GET request is made to /about.
  2. Test the new route by navigating to http://localhost:3000/about in your web browser.

Solution:

// Add this code to app.js

// Define a route handler for the /about page
app.get('/about', (req, res) => {
  res.send('About Us');
});

Exercise 2: Change the Port Number

  1. Change the port number from 3000 to 4000.
  2. Restart the server and verify that it is running on the new port.

Solution:

// Change this line in app.js
const port = 4000;

Common Mistakes and Tips

  • Common Mistake: Forgetting to restart the server after making changes to app.js.
    • Tip: Always restart the server to see the changes. You can use tools like nodemon to automatically restart the server when changes are detected.
  • Common Mistake: Using a port number that is already in use.
    • Tip: Ensure the port number you choose is not being used by another application.

Summary

In this section, you learned how to set up a basic Express application. You installed Express, created a simple application, defined routes, and started the server. You also completed exercises to reinforce your understanding. In the next section, we will dive deeper into middleware and how to use it in your Express applications.

Node.js Course

Module 1: Introduction to Node.js

Module 2: Core Concepts

Module 3: File System and I/O

Module 4: HTTP and Web Servers

Module 5: NPM and Package Management

Module 6: Express.js Framework

Module 7: Databases and ORMs

Module 8: Authentication and Authorization

Module 9: Testing and Debugging

Module 10: Advanced Topics

Module 11: Deployment and DevOps

Module 12: Real-World Projects

© Copyright 2024. All rights reserved