1

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)
    }
}
1
  • Are you using express? Commented Jun 21, 2022 at 18:28

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.