Jonas Mohr Pedersen
Jonas Mohr Pedersen

Reputation: 555

Node.js - Return res.status VS res.status

I am curious about the difference of returning a response and just creating a response.

I have seen a vast amount of code examples using both return res.status(xxx).json(x) and res.status(xxx).json(x).

Is anyone able to elaborate on the difference between the two?

Upvotes: 11

Views: 13533

Answers (3)

eo33
eo33

Reputation: 13

The return statement will terminate the function and not go any further. For example, if you have a middleware function that return res.status(xxx).json(x), the next function (middleware or final handler) will stop executing since a response has already been return. However, if you did not return the response, it will continue executing the next function in the sequence.

Upvotes: 1

adius
adius

Reputation: 14962

As explained by @kasho, this is only necessary for short-circuiting the function. However, I would not recommend to return the send() call itself, but rather after it. Otherwise it gives the wrong expression, that the return value of the send() call was important, which it isn't, as it is only undefined.

if (!isAuthenticated) {
  res.sendStatus(401)
  return
}

res
  .status(200)
  .send(user)

Upvotes: 15

kasho
kasho

Reputation: 526

If you have a condition and you want to exit early you would use return because calling res.send() more than once will throw an error. For example:

//...Fetch a post from db

if(!post){
  // Will return response and not run the rest of the code after next line
  return res.status(404).send({message: "Could not find post."})
}

//...Do some work (ie. update post)

// Return response
res.status(200).send({message: "Updated post successfuly"})

Upvotes: 15

Related Questions