Routing in Express: What You Need to Know
Routing in Express is a crucial process that determines the appropriate action to take when a specific URL is called or when a particular incoming request needs to be handled. Without proper routing, an application may fail to deliver the desired functionality.
In our previous example of the Hello World application, we used the following code:
1 | app.get('/', (req, res) => { /* code here */ }) |
This code snippet creates a route that maps the root domain URL (/
) using the HTTP GET method to the desired response.
Named Parameters: Creating Custom Requests
At times, we might want to listen for custom requests, such as creating a service that accepts a string and returns its uppercase version. In such cases, it might be inconvenient to send the parameter as a query string. Instead, we can include it as part of the URL by using named parameters.
For instance:
1 | app.get('/uppercase/:theValue', (req, res) => res.send(req.params.theValue.toUpperCase())) |
If we send a request to /uppercase/test
, the response body will contain the string TEST
in uppercase.
It’s worth noting that we can use multiple named parameters within the same URL, and all these parameters will be stored in the req.params
object.
Matching Paths Using Regular Expressions
Express allows us to use regular expressions to match multiple paths using a single statement.
For example:
1 | app.get(/post/, (req, res) => { /* code here */ }) |
This code will match URLs such as /post
, /post/first
, /thepost
, /posting/something
, and many others.
In summary, understanding how routing works in Express is crucial for building robust applications. By utilizing named parameters and regular expressions, we can create custom routes that enhance the overall functionality of our applications.
tags: [“Express routing”, “named parameters”, “regular expressions”]