Michael Nielsen
Michael Nielsen

Reputation: 1242

NodeJS REST API and res.json/res.send

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

Answers (1)

R. Gulbrandsen
R. Gulbrandsen

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

Related Questions