Home > other >  NodeJS - How to pass url parameter to controller function?
NodeJS - How to pass url parameter to controller function?

Time:10-16

I have this line in my router file.

app.get('/:catId', categoryController.getSingleCategoryById)

Now in controller how do I access the catId?

My controller code

function getSingleCategoryById(req, res) {
    categoryModel.findOne({
        where: {
            id: catId
        }
    }).then(data => {
        res.status(201).json({msg: "OK", payload: data})
    }).catch(err => {
        res.status(400).json({msg: "Error", err})
    }) 
}

CodePudding user response:

You can get it from params because you send it in the url.

const catId = req.params.catId

now you have assigned it to catId variable and you can use it.

  • Related