Is it possible to make router in ExpressJS like this?
users.js
const userController = ('../controllers/userController.js');
router.get('/:userName', userController.paramByUsername);
router.get('/:id', userController.paramByUserId);
In the controller, the code look like this
userController.js
function paramByUsername(req, res) {
User.findOne({
where: {
userId: req.params.userId
}
})
.then((user) => {
if(!user) {
return res.status(404).json({ message: "User not found."});
}
return res.status(200).json(user);
})
.catch((error) => {
return res.status(400).json(error);
});
}
function paramByUserId(req, res) {
User.findByPk(req.params.id)
.then((user) => {
if(!user) {
return res.status(404).json({ message: "User not found."});
}
}).catch((error) => {
return res.status(400).json(error);
});
}
By the code above, what I wanted to achieve is the endpoint like this:
/users/1
this should response same as /users/username
.
I have tried the code above, but what I see is an error when I get /users/:id