DEV Community

Pravin Jadhav
Pravin Jadhav

Posted on

How I Learned to Build My First Express.js Server

Introduction

Express.js is one of the most popular web frameworks for Node.js, allowing developers to build web applications and APIs efficiently. In this blog, we will break down an Express.js server, explain its components, and provide a deeper technical understanding of how it works.


Setting Up Express.js

Before diving into the code, ensure that Node.js is installed on your system. You can check this by running:

node -v
Enter fullscreen mode Exit fullscreen mode

If Node.js is installed, proceed with installing Express:

npm install express
Enter fullscreen mode Exit fullscreen mode

Now, let's create a basic Express.js server.


Writing a Simple Express.js Server

Here’s a simple Express.js server script:

const express = require('express');  // Import the Express library
const app = express();  // Create an Express application

// Define a route
app.get('/', (req, res) => {
    res.send('Hello, World!');  // Send response to client
});

// Start the server on port 3000
app.listen(3000, () => {
    console.log('Server is running on http://localhost:3000');
});
Enter fullscreen mode Exit fullscreen mode

Now, let's break it down step by step.


1️⃣ Importing Express

const express = require('express');
Enter fullscreen mode Exit fullscreen mode

Technical Explanation:

  • require('express'): This loads the Express module, which simplifies handling HTTP requests in Node.js.
  • The express variable now holds an instance of Express.

2️⃣ Creating an Express Application

const app = express();
Enter fullscreen mode Exit fullscreen mode

Technical Explanation:

  • express(): Initializes a new Express application.
  • This app object will be used to define routes, middleware, and server behavior.

3️⃣ Defining Routes

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

Technical Explanation:

  • app.get('/'): This part sets up a rule for your server that says, "When someone visits the main webpage (/), do something."

  • (req, res) => {}: This is the action you want to take when someone visits that page. It’s a function with two parts:

    • req: Represents the information coming from the person visiting the website (like who they are or where they're coming from).
    • res: This is what you send back to the visitor (like a message, a webpage, etc.).
  • res.send('Hello, World!'): When someone visits the website, the server will reply with "Hello, World!" as the message.

How Routes Work:

When a user visits http://localhost:3000/, this function executes and responds with "Hello, World!".


4️⃣ Starting the Server

app.listen(3000, () => {
    console.log('Server is running on http://localhost:3000');
});
Enter fullscreen mode Exit fullscreen mode

Technical Explanation:

  • app.listen(3000): Starts the server on port 3000.
  • The callback function inside listen() runs once the server starts successfully.

How Listening Works:

  • This makes your application accessible on http://localhost:3000.
  • The console.log message confirms that the server is running.

Extending Your Express.js Server

Now that you understand the basics, let's expand the server by adding:

➤ 1. Handling Different Routes

You can define multiple routes for different URLs:

app.get('/about', (req, res) => {
    res.send('About Page');
});

app.get('/contact', (req, res) => {
    res.send('Contact Page');
});
Enter fullscreen mode Exit fullscreen mode

➤ 2. Handling POST Requests

To accept POST requests, we need middleware to handle incoming data:

app.use(express.json());  // Middleware to parse JSON data

app.post('/submit', (req, res) => {
    res.send(`Received Data: ${JSON.stringify(req.body)}`);
});
Enter fullscreen mode Exit fullscreen mode

➤ 3. Using Middleware for Logging Requests

Middleware functions execute before sending a response. Let's log incoming requests:

app.use((req, res, next) => {
    console.log(`Request Method: ${req.method}, URL: ${req.url}`);
    next();  // Pass control to the next middleware or route
});
Enter fullscreen mode Exit fullscreen mode

Summary Table

Code Component Purpose
require('express') Imports the Express module
const app = express(); Creates an Express application instance
app.get('/', callback) Defines a route for GET requests at /
req Represents the HTTP request object
res Represents the response object
app.listen(3000) Starts the server on port 3000
app.use(middleware) Adds middleware for extra functionality

Conclusion

Express.js provides a powerful yet simple way to build web applications. We covered:

✅ Setting up an Express server

✅ Understanding routes and request-response handling

✅ Expanding functionality with middleware and different HTTP methods

Top comments (0)