Lesson 32 of 50 – Express Server
64% Completed
64%

Express Server in Node.js

Learn how to create and run a web server using Express.js, handle browser requests, send responses, and configure a server port.

Prerequisite: Complete the previous lesson, Introduction to Express.js. Make sure Node.js and Express.js are installed on your computer.

1. What Is an Express Server?

An Express server is a web server created with the Express.js framework. It listens for HTTP requests from browsers, mobile applications, or other clients and sends suitable responses.

For example, when a user opens:

http://localhost:3000

The browser sends a request to the server. Express processes the request and returns a response.

Request and Response Flow
Browser / Client

Sends HTTP request

↓
Express Server

Processes the request

↓
Browser / Client

Receives the response

2. Create an Express Server Project

First, create a project folder.

mkdir express-server
cd express-server

Initialize the Node.js project:

npm init -y

Install Express.js:

npm install express

Now create a file named app.js in the express-server folder.

3. Create Your First Express Server

app.js
const express = require('express');

const app = express();

app.get('/', (req, res) => {
    res.send('My First Express Server');
});

app.listen(3000, () => {
    console.log('Server running on port 3000');
});

Code Explanation

  • require('express') imports Express.js.
  • express() creates the Express application.
  • app.get() handles a GET request to the specified route.
  • req contains information about the incoming request.
  • res.send() sends a response to the client.
  • app.listen(3000) starts the server on port 3000.

4. Run the Express Server

Open your terminal in the project folder and run:

node app.js

Expected terminal output:

Server running on port 3000

Open this URL in your browser:

http://localhost:3000
Browser Output:

My First Express Server

Important: Keep the terminal running while you test the application. Press Ctrl + C in the terminal to stop the server.

5. Create Multiple Routes

An Express server can respond differently depending on the URL requested by the client.

Example: Home, About, and Contact
const express = require('express');

const app = express();

app.get('/', (req, res) => {
    res.send('Welcome to the Home Page');
});

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

app.get('/contact', (req, res) => {
    res.send('Contact Us');
});

app.listen(3000, () => {
    console.log('Server running on port 3000');
});

Test these URLs:

  • http://localhost:3000/
  • http://localhost:3000/about
  • http://localhost:3000/contact

6. Send HTML Responses

You can use res.send() to send HTML content to the browser.

Example: HTML Response
const express = require('express');

const app = express();

app.get('/', (req, res) => {
    res.send(`
        <html>
            <head>
                <title>My Website</title>
            </head>
            <body>
                <h1>Welcome Student!</h1>
                <p>This page is served by Express.js.</p>
            </body>
        </html>
    `);
});

app.listen(3000, () => {
    console.log('Server running on port 3000');
});

The browser renders the HTML instead of displaying the HTML tags as ordinary text.

7. Send JSON Responses

JSON is commonly used to exchange data between a server and a website or mobile application.

Example: Student API
const express = require('express');

const app = express();

app.get('/student', (req, res) => {
    res.json({
        id: 101,
        name: 'Amit',
        course: 'Node.js'
    });
});

app.listen(3000, () => {
    console.log('Server running on port 3000');
});

Open:

http://localhost:3000/student

Expected response:

{
  "id": 101,
  "name": "Amit",
  "course": "Node.js"
}

8. Use a Custom Port

A port is a communication endpoint used by applications on a computer. You can configure Express to listen on a different port.

Example: Server on Port 5000
const express = require('express');

const app = express();

app.get('/', (req, res) => {
    res.send('Express server running on port 5000');
});

app.listen(5000, () => {
    console.log('Server running on port 5000');
});

Visit:

http://localhost:5000

9. Handle an Unknown Route

When a client requests a URL that does not match any route, you can return a custom 404 response.

Example: 404 Not Found
const express = require('express');

const app = express();

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

app.use((req, res) => {
    res.status(404).send('404 - Page Not Found');
});

app.listen(3000, () => {
    console.log('Server running on port 3000');
});

Open http://localhost:3000/unknown to test the 404 response.

Place this fallback middleware after your normal routes so that unmatched requests can reach it.

10. Use an Environment Variable for the Port

An environment variable allows the port to be configured without hard-coding it in the application.

Example: Configurable Port
const express = require('express');

const app = express();

const PORT = process.env.PORT || 3000;

app.get('/', (req, res) => {
    res.send('Express server is running');
});

app.listen(PORT, () => {
    console.log(`Server running on port ${PORT}`);
});

If PORT is provided by the environment, Express uses that value. Otherwise, it uses port 3000.

11. Common Express Server Errors

Error Possible Cause Solution
Cannot find module 'express' Express is not installed in the project. Run npm install express.
Cannot find module './app.js' Wrong folder or filename. Check your current directory and filename.
Port already in use Another process is using the port. Stop that process or select another port.
Cannot GET /about No matching GET route exists. Create the route or check the URL.

12. Practical Assignment

Assignment: Build a Small Express Website

Create an Express server with the following requirements:

  1. Create a project named my-website.
  2. Install Express.js.
  3. Create a home page displaying your name.
  4. Create an /about route displaying your course.
  5. Create a /services route listing three services.
  6. Create a /student route returning student data as JSON.
  7. Configure the server to use port 4000.
  8. Return a custom 404 message for unknown routes.
Lesson Summary: You learned to create an Express server, start it with app.listen(), handle multiple routes, send HTML and JSON responses, choose a port, and handle unknown routes.

Test Your Knowledge – MCQ Quiz

Select the correct answer for each question.

1. Which method starts an Express server?
2. Which method sends a JSON response?
3. What does HTTP status code 404 generally mean?