Introduction to Express.js: A Beginner's Guide

Introduction to Express.js: A Beginner's Guide

This blog will introduce you to the basics of Express.js, provide simple explanations, and walk you through a basic example to help you get started.

What is Express.js?

Express.js, or simply Express, is a minimal and flexible Node.js web application framework that provides a robust set of features to develop web and mobile applications. It allows you to handle routes, requests, and responses efficiently, making it easier to build web servers and APIs.

Why Use Express.js?

  1. Simplicity: Express provides a straightforward way to create server-side applications.

  2. Middleware Support: It allows you to use middleware to handle requests, responses, and errors.

  3. Routing: Express makes routing simple and manageable.

  4. Large Ecosystem: A vast collection of middleware and plugins are available, enhancing functionality.

Setting Up Express.js

Before diving into Express, ensure you have Node.js and npm installed. If not, refer to the official Node.js website to download and install them.

  1. Create a New Directory: Open your terminal and create a new directory for your project:

     cmkdir my-first-express-app
     cd my-first-express-app
    
  2. Initialize a New Node.js Project: Initialize a new Node.js project using npm:

     npm init -y
    

    This command creates a package.json file.

  3. Install Express: Install Express.js using npm:

     npm install express
    

Creating Your First Express.js Application

Now, let’s create a basic Express application.

  1. Create an Entry File: Create a new file named app.js in your project directory.

  2. Write Your First Express Code: Open app.js in your favorite code editor and add the following code:

     // Import the express module
     const express = require('express');
    
     // Create an Express application
     const app = express();
    
     // Define a port to listen on
     const PORT = 3000;
    
     // Define a route handler for the root URL ("/")
     app.get('/', (req, res) => {
       res.send('Hello, World from Express!');
     });
    
     // Start the server and listen on the defined port
     app.listen(PORT, () => {
       console.log(`Server is running on http://localhost:${PORT}`);
     });
    
  3. Run Your Application: Go back to your terminal and run the following command:

     node app.js
    

    You should see the message Server is running on http://localhost:3000 in your terminal.

  4. View Your Application: Open your web browser and navigate to http://localhost:3000. You should see the text "Hello, World from Express!" displayed.

Understanding the Code

Let’s break down the code we just wrote:

  • Importing Express: We use require('express') to import the Express module.

  • Creating an Express Application: The express() function creates an Express application instance.

  • Defining a Route: The app.get method defines a route handler for the HTTP GET request to the root URL (/). When this route is accessed, it sends "Hello, World from Express!" as a response.

  • Starting the Server: The app.listen method starts the server on the specified port (3000) and logs a message when the server is ready.

Adding More Routes

Let's add a few more routes to our application:

  1. Add a New Route: Update app.js to include additional routes:

     // Import the express module
     const express = require('express');
    
     // Create an Express application
     const app = express();
    
     // Define a port to listen on
     const PORT = 3000;
    
     // Define a route handler for the root URL ("/")
     app.get('/', (req, res) => {
       res.send('Hello, World from Express!');
     });
    
     // Define a route handler for "/about"
     app.get('/about', (req, res) => {
       res.send('About Us');
     });
    
     // Define a route handler for "/contact"
     app.get('/contact', (req, res) => {
       res.send('Contact Us');
     });
    
     // Start the server and listen on the defined port
     app.listen(PORT, () => {
       console.log(`Server is running on http://localhost:${PORT}`);
     });
    
  2. Run Your Application: Restart your server by running the following command in your terminal:

     node app.js
    
  3. View Your Application:

    • Navigate to http://localhost:3000/about to see the "About Us" message.

    • Navigate to http://localhost:3000/contact to see the "Contact Us" message.

Next Steps

Now that you have a basic understanding of Express.js, here are a few topics to explore next:

  1. Middleware: Learn how to use middleware for logging, authentication, and more.

  2. Static Files: Serve static files like HTML, CSS, and JavaScript.

  3. Templating Engines: Integrate a templating engine like EJS, Pug, or Handlebars for dynamic content.

  4. APIs: Build RESTful APIs to interact with frontend applications or other services.

  5. Database Integration: Connect your Express application to a database like MongoDB or MySQL.