Reputation: 1242
I'm building a REST API in nodejs, and would like to verify data params before doing anything else.
Can I simply do:
(req.body.X != XYZ)
res.json({ error: fail })
// continue
Or should I do:
if (req.body.X != XYZ) {
res.json({ error: fail })
} else {
// continue
}
Upvotes: 0
Views: 349
Reputation: 3778
if you use the return keyword you'll stop the function, and return a value. So you can do
if (req.body.X !== XYZ) {
return res.json({error: fail});
}
// continue
Comparing values in JS should be done with === or !== to be safe :)
Also, I would recommend you use res.status(400/500/401).send(message) for error messages so that the correct http status is set on your response
Upvotes: 1