In JavaScript, we can create a URL router using regular expressions (regex). This is useful when we want to map different URL patterns to specific functions, handlers or controllers. Here's an example of how to create a simple router using Node.js:
index.tsx1268 chars61 lines
This router uses an object called routes
to map different URL patterns to specific handler functions. The /*
route is a catch-all for any other URLs that don't match any of the other patterns.
The router uses a regular expression to match the URL pattern with the incoming request URL. The expression replaces any :param
segments in the route with a regex match for one or more word characters. This allows us to extract the value of any parameter segments in the URL.
The router also uses the req.params
object to extract any parameter values and pass them to the corresponding handler function. This makes it easy to access and use parameter values in the handler.
With this router, you can easily create more handlers for other URL patterns by adding to the routes
object.
gistlibby LogSnag