express route parameters

Express Route Parameters

Express is a popular Node.js framework for building web applications. One of the key features of Express is its routing system. Express routes are used to map URLs to handler functions, allowing you to create a RESTful API or serve dynamic HTML files.

Route parameters are used to capture dynamic segments of the URL, allowing you to create flexible routes that can handle a variety of requests. For example, if you have a route for /users/:id, the :id parameter will capture any value that comes after /users/ and make it available in the request object.

Basic Route Parameter Example

Here's an example of a route with a parameter:

app.get('/users/:id', (req, res) => {
  const userId = req.params.id;
  // Do something with userId
});

In this example, any request to /users/123 will trigger this route, and the value 123 will be available as req.params.id in the handler function.

Optional Route Parameters

You can make a route parameter optional by adding a question mark (?) at the end of the parameter:

app.get('/users/:id?', (req, res) => {
  const userId = req.params.id || 'default';
  // Do something with userId
});

In this example, the :id parameter is optional, so a request to /users will trigger this route as well. If no ID is provided in the URL, the default value of 'default' will be used.

Regular Expression Route Parameters

You can use regular expressions to constrain the values that can be captured by a route parameter. For example, if you only want to capture IDs that are six digits long, you could use the following route:

app.get('/users/:id(\\d{6})', (req, res) => {
  const userId = req.params.id;
  // Do something with userId
});

In this example, the :id parameter is constrained to match six digits using the regular expression \d{6}.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe