Search code examples
node.jshttpexpressresponse

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?


Solution

  • 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"})