Express Routing

Routing refers to determining how an application responds to a client request to a particular endpoint, which is a URI (or path) and a specific HTTP request method (GET, POST, and so on).

1. Basic Routing

Each route can have one or more handler functions, which are executed when the route is matched.

app.get('/', (req, res) => {
  res.send('GET request to Homepage');
});

app.post('/user', (req, res) => {
  res.send('POST request to create a user');
});

app.put('/user/:id', (req, res) => {
  res.send('PUT request to update user');
});

app.delete('/user/:id', (req, res) => {
  res.send('DELETE request to remove user');
});

2. Route Parameters

Route parameters are named URL segments that are used to capture the values specified at their position in the URL. They are stored in req.params.

// URL: http://localhost:3000/users/42/books/101
app.get('/users/:userId/books/:bookId', (req, res) => {
  const { userId, bookId } = req.params;
  res.send(`User ID: ${userId}, Book ID: ${bookId}`);
});

3. Query Strings

Query strings are used to pass optional parameters in the URL, usually for filtering or sorting. Available in req.query.

// URL: http://localhost:3000/search?q=nodejs&sort=asc
app.get('/search', (req, res) => {
  const { q, sort } = req.query;
  res.send(`Searching for ${q} sorted by ${sort}`);
});

4. The Express Router

For large applications, you should use express.Router to split your routes into separate files.

// routes/user.js
const express = require('express');
const router = express.Router();

router.get('/', (req, res) => res.send('All Users'));
router.get('/:id', (req, res) => res.send('One User'));

module.exports = router;

// app.js
app.use('/users', require('./routes/user'));