Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 948
Jonas Mohr Pedersen Avatar asked Oct 21 '18 20:10

Jonas Mohr Pedersen


People also ask

What is the difference between Res send and RES status?

There is no actual difference between res. send and res.

What is difference between Res send and res end?

res. send() is used to send the response to the client where res. end() is used to end the response you are sending.

Does Res end return?

Simply doing res. end does not work, neither does return res.

What is RES return?

send() Send a string response in a format other than JSON (XML, CSV, plain text, etc.). This method is used in the underlying implementation of most of the other terminal response methods.


2 Answers

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"})
like image 75
kasho Avatar answered Nov 15 '22 04:11

kasho


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)
like image 39
adius Avatar answered Nov 15 '22 03:11

adius