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:
- 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.
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
Method | Purpose | Example Use |
---|---|---|
GET | Read data | View home page |
POST | Submit data | Submit a form |
PUT | Update existing data | Update a user profile |
DELETE | Remove data | Delete an account |
1.3 Route Parameters (req.params)
These are variables in the URL. Like:
/product/:id
Visiting /product/123 → shows: Product ID: 123
/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
Visiting /search?q=laptop → shows: You searched for: laptop
/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