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}!`));

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.