Sebastian Dahlgren
Sebastian Dahlgren

Reputation: 967

Why is an explicit return required in ExpressJS

I have a small function like this:

tierRouter.get(
  '/:id',
  passport.authenticate('basic', { session: false }),
  function (req, res) {
    Tier.findById(req.params.id, function (err, tier) {
      if (err) { res.json(500, { error: "Internal server error" }); }
      if (!tier) { return res.json(404, { error: "Not found" }); }
      res.json(200, clean(tier));
    });
  }
);

It looks for an object in my database and returns it as JSON to the user. If something goes wrong I get a 500 returned and if everything goes well I return 200 and the object. But when the object does not exist I return 404. The only difference is that I have to write return before the res.json in the 404 case, or else Node will continue to res.json(200, clean(tier));.

I just don't understand why I have to add the return statement. Can someone explain that or kick me in the right direction?

Upvotes: 0

Views: 110

Answers (1)

Jonathan Ong
Jonathan Ong

Reputation: 20345

you need either early return or do a lot of if/else statements. otherewise, if you do res.render() or res.json() more than once on a request, you're going to get a headers already sent error and crash everything

Upvotes: 3

Related Questions