Best way to handle query params #697
-
I have the following handler:
But I would like to have a handler to return cars of a specific make (via query params) so I thought something like this would work:
But this throws a warning. Would something like this be ok?
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
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 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))
})
|
Beta Was this translation helpful? Give feedback.
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 viareq.url.searchParams
, and base your response on that value.