Creating Your First Express.js Server

Write your first Express.js application and understand the basic structure of an Express.js server. Learn about routing and handling HTTP requests.


Mastering Express.js: Build Scalable Web Applications

Creating Your First Express.js Server

Express.js is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications. It simplifies Node.js development and makes creating web servers much easier.

This section will guide you through the steps of setting up your first Express.js server and understanding its fundamental structure.

Writing Your First Express.js Application

Prerequisites

  • Node.js installed on your machine. You can download it from nodejs.org.
  • A code editor (e.g., VS Code, Sublime Text, Atom).
  • Basic understanding of JavaScript.

Steps

  1. Create a Project Directory: Create a new folder for your project. For example, name it `my-express-app`.

    mkdir my-express-app
    cd my-express-app
  2. Initialize npm: Inside the project directory, initialize npm (Node Package Manager) to manage dependencies.

    npm init -y

    This command creates a `package.json` file in your directory with default settings.

  3. Install Express: Install the Express.js package as a dependency.

    npm install express
  4. Create the Server File: Create a JavaScript file (e.g., `app.js` or `server.js`) where you will write your Express.js code.

    touch app.js
  5. Write the Express.js Code: Open `app.js` in your code editor and add the following code:

     const express = require('express');
    const app = express();
    const port = 3000;
    
    app.get('/', (req, res) => {
      res.send('Hello World!');
    });
    
    app.listen(port, () => {
      console.log(`Example app listening at http://localhost:${port}`);
    }); 
  6. Run the Application: In your terminal, run the application using Node.js.

    node app.js
  7. Test the Application: Open your web browser and go to http://localhost:3000. You should see "Hello World!" displayed on the page.

Understanding the Basic Structure of an Express.js Server

Let's break down the code snippet we used above:

  • `require('express')`:** This line imports the Express.js module and makes its functions available. Think of it as importing a library into your code.

  • `const app = express()`:** This creates an instance of the Express application. `app` is now an object with methods to handle routing, middleware, and more.

  • `const port = 3000`:** This defines the port number on which the server will listen for incoming requests. You can change this to any available port.

  • `app.get('/', (req, res) => { ... })`:** This defines a route handler for GET requests to the root path ('/').

    • `app.get()` is a method to handle GET requests.
    • `'/'` is the route path (root in this case).
    • `(req, res) => { ... }` is a callback function that executes when a GET request is made to the '/'.
    • `req` (request) contains information about the incoming request (e.g., headers, query parameters).
    • `res` (response) is an object used to send a response back to the client.
    • `res.send('Hello World!')` sends the string "Hello World!" as the response.
  • `app.listen(port, () => { ... })`:** This starts the server and listens for incoming connections on the specified port.

    • `app.listen()` starts the server.
    • `port` is the port number to listen on.
    • `() => { ... }` is a callback function that executes once the server is running. This is where you can log a message to the console to confirm the server is started.

Key takeaways: Express uses the concept of middleware to handle requests. Route handlers like `app.get()` are essentially middleware functions. You can chain multiple middleware functions together to perform various tasks on a request before sending a response.