A route pairs an HTTP method and a URL pattern with a function to run when a request matches both. This lesson covers the pieces beyond the plain app.get() calls from the last lesson.
Express has a matching method for each HTTP verb:
app.get('/products', (req, res) => { /* fetch and list products */ })
app.post('/products', (req, res) => { /* create a new product */ })
app.put('/products/:id', (req, res) => { /* replace a product */ })
app.delete('/products/:id', (req, res) => { /* delete a product */ })| Method | Conventionally used for |
|---|---|
| GET | Reading data — should never change anything on the server |
| POST | Creating something new |
| PUT | Replacing an existing item entirely |
| DELETE | Removing something |
A colon in a route path captures part of the URL as a named value:
app.get('/products/:id', (req, res) => {
res.send(`Product ID: ${req.params.id}`)
})
// GET /products/42 → req.params.id is '42'A route can capture more than one:
app.get('/users/:userId/orders/:orderId', (req, res) => {
res.send(`User ${req.params.userId}, order ${req.params.orderId}`)
})Everything after a ? in a URL — /search?q=laptop&sort=price — is parsed automatically into req.query:
app.get('/search', (req, res) => {
res.send(`Searching for: ${req.query.q}, sorted by: ${req.query.sort}`)
})Params vs. query strings
Route parameters (/products/:id) identify a specific resource — usually required for the route to make sense at all. Query strings (?sort=price) are optional modifiers — filters, sorting, pagination — that change how the results come back.
As routes grow past a handful, express.Router() lets them live in their own file instead of piling up in one:
// routes/products.js
const express = require('express')
const router = express.Router()
router.get('/', (req, res) => { res.send('All products') })
router.get('/:id', (req, res) => { res.send(`Product ${req.params.id}`) })
module.exports = router
// app.js
const productsRouter = require('./routes/products')
app.use('/products', productsRouter)Every path inside routes/products.js is relative to whatever prefix it's mounted at — router.get('/:id') here actually matches /products/:id.