I am making a post request and I want to check if any parameter is not left empty. It is being checked for one parameter but not for both.
app.post("/tshirt/:id", (req, res) => {
const {id} = req.params;
const {logo, size} = req.body;
if(logo === undefined) {
res.status(418).send("It needs a logo");
}
if(size === undefined) {
res.status(418).send("It needs a size");
}
else {
res.status(200).send({
tshirt: `👕 with your ${logo} is ready`,
size: `${size}`
});
}
})
When no size is passed
When no logo is passed
When both parameters are passed
I want to get the result only when both the parameters are satisfied.
2
Answers
pay attention to use return in sending response.
Personally, I would return an "error" response if either one or both properties aren’t set, with an appropriate message for each case
So, in the code below, the "error" message can either be
.
app.post("/tshirt/:id", (req, res) => {
const {id} = req.params;
const {logo, size} = req.body;
Though, to reduce the nesting of
if
, I’d probably do it like this (though, many people prefer to handle error cases first)