Home > front end >  How do I add multiple optional parameters in Express in same route
How do I add multiple optional parameters in Express in same route

Time:09-25

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.

CodePudding user response:

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' }
})
  • Related