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

180
Visualizações
How do I add multiple optional parameters in Express in same route

Big fan of Stackoverflow and this is my first question ever on it! I'm working on a javascript express project and trying to figure out if I can do this under one get request. I'm having a hard time figuring this out

app.get("/test/:q1&:q2&:q3", (req, res) => {
  console.log(req.params)
})

Basically, when the user looks up the following routes, I want the following result in req.params when these get requests are made. I want to keep it under one get request if possible.

TO CLARIFY. The above code CAN change to meet the functional requirements BELOW. Below CANNOT change

"http://localhost:3000/test/hello" --->
req.params will equal { q1: "hello" }

"http://localhost:3000/test/hello&world" --->
req.params will equal { q1: "hello", q2: "world" }

"http://localhost:3000/test/hello&world&foobar" --->
req.params will equal { q1: "hello", q2: "world", q3: "foobar" }

I tried using the "?" in the query but it seems to only work on new routes followed by a "/", not within the same route. I'm thinking I'll have to go with the quick and dirty solution of making 2 more get requests for each scenario. Currently when I try putting in "/test/hello&world" or "/test/hello", it will crash and will only work if I have all 3 parts filled.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Can you try this?

app.get('/test/:string', (req, res) => {
  const str = req.params.string
  const params = str.split('&')
    .reduce((acc, curr, i) => ({ ...acc, [`q${i + 1}`]: curr }), {})

  // params => { q1: 'hello', q2: 'world', q3: 'foobar' }
})
about 4 years ago · Juan Pablo Isaza 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