Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

246
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda