So let's say we have the following url:
http://example.com/shops/map/search
I want to access the second segment (map) and check its value. How can I achieve this in Express? Thanks in advance!
So let's say we have the following url:
http://example.com/shops/map/search
I want to access the second segment (map) and check its value. How can I achieve this in Express? Thanks in advance!
you have to configure your express routes to accept url segments.
app.get('/shops/:type/search', function (req, res) {
res.send(req.params)
})
For a request like this http://example.com/shops/map/search
req.params will contain required URL segment.
Request URL: http://example.com/shops/map/search
req.params: { "type": "map" }
You can use a route parameters with a constant set of values.
Express uses path-to-regexp
to parse the strings you provide for routes. That package permits providing a custom pattern with a parameter to limit the values that can be matched.
app.get('/shops/:kind(list|map)/search', searchShops);
The contents of the parenthesis, (...)
, are a partial RegExp pattern, in this case equivalent to:
/(?:list|map)/
# within a non-capturing group, match an alternative of either "list" or "map" literally
Then, within searchShops
, you can determine which value was given with req.params
:
function searchShops(req, res) {
console.log(req.params.kind); // 'list' or 'map'
// ...
}
Alternatively, you can leave the parameter open, checking the value within the handler, and invoke next('route')
when the value isn't acceptable:
app.get('/shops/:kind/search', searchShops);
var searchKinds = ['list', 'map'];
function searchShops(req, res, next) {
if (!searchKinds.includes(req.params.kind)) return next('route');
// ...
}
You can access the url segments by splitting the url into an array. Like this:
let requestSegments = req.path.split('/');
The original answer does the job, but leaves you with an empty element in the array. I'd use the following slight variation to solve this too.
let requestSegments = req.path.split('/').filter((s) => { return s !== ''});