Reputation: 3153
Hello i have array of objects validation inside my async function (router.post()) and i need to map it before validating and this is how I do it
ingredients.map(({ingredient,quantity})=>{
if(ingredient.trim().length < 1 || quantity.length < 1){
return res.status(409).send({
message: ''
})
}
})
and after this i send 200 status code to client side (ReactJS) but it causes error
Can't set headers after they are sent
i do not know what is problem with this.
before this block of code i have only if statements to validate other inputs and when i commented this block of code the if statements worked. So what is problem with this?
P.S: I stringified array before sending the server and then parsed of course
EDIT: it does not causes errors when everything is ok and ingredient or quanitity is not empty
Upvotes: 0
Views: 56
Reputation: 7675
The issue occurs because res.send
is being called multiple times.
If your intention is to respond with 409
status code if at least one of ingredients is invalid, you can check if there is at least one invalid item and respond with 409
if it's there:
const hasInvalidIngredient = ingredients.some(
({ingredient,quantity}) => ingredient.trim().length == 0 || quantity.length == 0
)
if (hasInvalidIngredient) {
return res.status(409).send({
message: ''
})
}
Upvotes: 2