Routing in Express.JS

1.1 What is Routing

When a user makes a request to your server (like visiting a website or clicking a button), Express decides how to respond using routes.

Think of a route like this:
route.js
1app.get('/home', (req, res) => { 2 res.send("Welcome to Home Page!"); 3});

- app is your Express app instance.
- get is the HTTP method (others include post, put, delete).
- /home is the path (like going to localhost:3000/home).
- The function (req, res) => { } is called the route handler. It sends the response.

1.2 Different HTTP Methods

MethodPurposeExample Use
GETRead dataView home page
POSTSubmit dataSubmit a form
PUTUpdate existing dataUpdate a user profile
DELETERemove dataDelete an account

1.3 Route Parameters (req.params)

These are variables in the URL. Like:

/product/:id

1app.get('/product/:id', (req, res) => { 2 res.send(`Product ID: ${req.params.id}`); 3});

Visiting /product/123 → shows: Product ID: 123

1.4 Query Parameters (req.query)

Used like this in the URL:

/search?q=laptop

1app.get('/search', (req, res) => { 2 const q = req.query.q; 3 res.send(`You searched for: ${q}`); 4});

Visiting /search?q=laptop → shows: You searched for: laptop