I am using express and trying to create an API endpoint to accept a GET request like GET /dogs?breed=GOLDEN&name=rex
.
What is the best approach to pass parameters into a url? While testing, I created two endpoints as shown below. Neither return a success
router.get('/dogs?breed=GOLDEN&name=rex', breedAndNameController.fetch);
router.get('/dogs?breed=:breed&name=:name', breedAndNameController.fetch);
export const fetch = async (req: any, res: any) => {
try {
console.log("success")
return res.status(200).send("success");
} catch (err) {
console.log(err)
}
}
CodePudding user response:
It looks like you're using express.js (just a guess).
Query-params are not a part of your route.
You have two options now:
Use query strings
Using query-string arguments your url looks like this:
router.get('/dogs', breedAndNameController.fetch);
And your route:
export const fetch = async (req: any, res: any) => {
try {
console.log(req. query);
return res.status(200).send("success");
} catch (err) {
console.log(err)
}
}
The call looks like /dogs?breed=asdf&name=test
Use params
Using params your url looks like this:
router.get('/dogs/:breed/:name', breedAndNameController.fetch);
which gives you access like this:
export const fetch = async (req: any, res: any) => {
try {
console.log(req.params)
return res.status(200).send("success");
} catch (err) {
console.log(err)
}
}
And your url looks like /dogs/tset/asdf
.
CodePudding user response:
You should keep your route as /dogs
and supply the query params when you actually call the query
router.get('/dogs', breedAndNameController.fetch);
and then you make a request to as /dogs?breed=GOLDEN&name=rex