Skip to content

Best way to handle query params #697

Answered by kettanaito
cmacdonnacha asked this question in Q&A
Discussion options

You must be logged in to vote

Hi, @cmacdonnacha.

Query parameters shouldn't be present in the request handler URL as they aren't a part of the resource's path. You're handling the query parameters correctly in the last example: create a resource path /cars, access the parameter value via req.url.searchParams, and base your response on that value.

const mockCars = [
  { id: 1, make: 'ford', color: 'red' }
]

res.get('/cars', (req, res, ctx) => {
  const manufacturer = req.url.searchParams.get('make')
  const cars = mockCars.filter(car => car.make === manufacturer)
  
  if (cars.length === 0) {
    return res(ctx.status(404))
  }

  return res(ctx.json(cars))
})

You can also read more about working with URL query param…

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@cmacdonnacha
Comment options

Answer selected by kettanaito
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants