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?
There is no actual difference between res. send and res.
res. send() is used to send the response to the client where res. end() is used to end the response you are sending.
Simply doing res. end does not work, neither does return res.
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.
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"})
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With