简体   繁体   中英

Typescript - How do you create a GET endpoint with params?

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)
    }
}

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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM