How to write API with multiple parameter in express.js

Viewed 878

I'm a bit new to Node.js and writing some GET REST APIs in Express.js. For one of my API, I need to pass 2 parameters to get the data from the database. I have achieved it using a single parameter but not more than 2. anyone help me, please?

Here my function

getByNPPTahunBulan(req,res){
        console.log(req.param.tahun_bulan)
        Iuran_Dapen.findAll({
            where: {
                tahun_bulan: req.params.tahun_bulan,
                npp: req.param.npp
            }
        }).then((data) => {
            return res.send(data);
            }).catch((err) => {
                res.status(500).send({
                    message: err.message || 'Some error occurred while retrieving data.',
                });
            })
    },

and the url router.get('/iuranterakhir/:tahun_bulan/:npp', iuranDapen.getByNPPTahunBulan);

1 Answers

req.params contains a parameter object with its respective value with the following url /:id/:name ej.

{
    'id': 1,
    'name': 'foo'
}

and you can do something like this:

const params = req.params;

and access as follows

params.id or params.name

the keys of the objects depends on the name of the parameters that you have given in the definition of your endpoint

Related