Express.js Complete Roadmap for Students and Developers Lesson 2 of 21

Routes and HTTP Requests in Express.js

Free preview — first two lessons of this course.

Register and unlock the full course to read every chapter and track progress in your learning hub.

Welcome to Shrash Studio Learning. In this tutorial, we will learn Routes and HTTP Requests in Express.js using super simple English, practical examples, and beginner-friendly explanations.

What is a Route in Express.js?

A route is simply:

A path inside your Express application.

Different Routes Example

Route Purpose
/api/users Returns users list
/api/products Returns products list
/api/orders Returns orders list

Common HTTP Methods

Method Purpose
GET Retrieve data
POST Create data
PUT Update data
DELETE Delete data

Creating First Route


app.get('/', (req, res) => {

    res.send('Hello World');

});

Sending JSON Response


app.get('/', (req, res) => {

    res.send({
        message: 'Hello World'
    });

});

Setting HTTP Status Code


app.get('/', (req, res) => {

    res.status(201).send({
        message: 'Created Successfully'
    });

});

Creating Users Route


app.get('/api/users', (req, res) => {

    res.send([
        {
            id: 1,
            username: 'anson',
            displayName: 'Anson'
        },
        {
            id: 2,
            username: 'jack',
            displayName: 'Jack'
        }
    ]);

});

Creating Products Route


app.get('/api/products', (req, res) => {

    res.send([
        {
            id: 1,
            name: 'Chicken Breast',
            price: 12.99
        },
        {
            id: 2,
            name: 'Rice',
            price: 5.99
        }
    ]);

});

Complete Example


import express from 'express';

const app = express();

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

app.get('/', (req, res) => {

    res.send('Hello World');

});

app.get('/api/users', (req, res) => {

    res.send([
        {
            id: 1,
            username: 'anson',
            displayName: 'Anson'
        }
    ]);

});

app.get('/api/products', (req, res) => {

    res.send([
        {
            id: 1,
            name: 'Chicken Breast',
            price: 12.99
        }
    ]);

});

app.listen(port, () => {

    console.log(`Running on port ${port}`);

});

Important Tips

  • Use meaningful route names
  • Always use /api prefix
  • Keep routes organized
  • Use correct HTTP methods
  • Return proper status codes

Interview Answer

If interviewer asks "What is a Route in Express.js?"

"A route in Express.js is a path or endpoint that handles client requests and returns responses from the server."

Summary

Routes are one of the most important concepts in Express.js because they help handle client requests and send responses properly.

Understanding routes and HTTP methods is extremely important for backend and full-stack developers.

Back to course overview