Skip to content
the poor coder

express route parameters

Poor Man
Published
Reading time
1 min read
On this page

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:

Text
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:

Text
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:

Text
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}.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC