Learning Express: Part 3: Dynamic Routing

Learning Express

Express is a popular minimalist web framework for Node.js.


Dynamic Routing

Because routes are based on path strings supplied via HTTP method name functions on the Application object in Express, it is possible to create dynamic routing where values can be parsed from the requested URI.

When a colon is used with a path, Express translates the resulting Request URI segment from the previous slash to the next slash (or ending of the string) into its params object as a named property.

For example, if the the URI “/users/:id” was used by a client, it would create a named property id on the request.params object.

const express = require('express');
const app = express();
const port = 3000;

app.get('/users/:id', (request, response) => {
    response.send(`Received id ${request.params.id}`);
});

app.listen(port, () => console.log(`Example app listening on port ${port}!`));

Multiple values can also be passed as parameters in this way.

const express = require('express');
const app = express();
const port = 3000;

app.get('/users/:id/:comment', (request, response) => {
    response.send(
        `Received id ${request.params.id} and comment is ${request.params.comment}`
    );
});

app.listen(port, () => console.log(`Example app listening on port ${port}!`));