Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

244
Views
How to access URL segment(s) in ExpressJS

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!

about 4 years ago · Santiago Trujillo
3 answers
Answer question

0

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" }
about 4 years ago · Santiago Trujillo Report

0

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');

    // ...
}
about 4 years ago · Santiago Trujillo Report

0

You can access the url segments by splitting the url into an array. Like this:

let requestSegments = req.path.split('/');
about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!