Loading

Quipoin Menu

Learn • Practice • Grow

express-js / ExpressJS Routing Basics
tutorial

ExpressJS Routing Basics

Imagine you are at a hotel. You ask the receptionist, "Where is the restaurant?" The receptionist points you to the right direction. In Express.js, routing works exactly like that receptionist – it directs incoming requests to the right place.

What is Routing?

Routing is how an application responds to client requests for specific endpoints. These endpoints are URLs (or paths) and specific HTTP methods (like GET, POST).

For example, when a user visits http://localhost:3000/about in their browser, they are making a GET request to the '/about' path. Express needs to know what to send back.

Basic Route Structure

A route definition in Express has this basic structure:
app.METHOD(PATH, HANDLER)
Where:
  • app is an instance of Express
  • METHOD is an HTTP method in lowercase (get, post, put, delete, etc.)
  • PATH is the URL path (like '/', '/about', '/contact')
  • HANDLER is a function that runs when the route is matched. It receives the request and response objects.

Simple Example
const express = require('express');
const app = express();

// Home page route
app.get('/', (req, res) => {
res.send('Welcome to our website!');
});

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

// Contact page route
app.get('/contact', (req, res) => {
res.send('Contact us at contact@example.com');
});

app.listen(3000);

What Happens When You Visit a URL?

  • When you visit http://localhost:3000/, Express looks for a route that matches GET '/' and sends "Welcome to our website!"
  • When you visit http://localhost:3000/about, it matches GET '/about' and sends the about page message.
  • If you visit a path that doesn't exist, like /xyz, Express will respond with a 404 Not Found error.

The Request and Response Objects

Every route handler receives two important objects:
  • req (Request): Contains information about the incoming request, like URL, parameters, query strings, and body data.
  • res (Response): Used to send a response back to the client, like HTML, JSON, or files.

Two Minute Drill
  • Routing directs requests to specific handlers based on URL and HTTP method.
  • Basic syntax: app.METHOD(PATH, HANDLER).
  • Use res.send() to send a response.
  • Express automatically handles 404 for undefined routes.

Need more clarification?

Drop us an email at career@quipoinfotech.com