Skip to content
Advertisement

What the return statement would do inside the router.post in nodejs [closed]

I was going through my organisations code where I found a code similar to below

router.post('/listings', async (req, res) => {
    //some thing related to req
    return res.status(200).json({
        code: 200,

    })
})

Where exactly the return statement is received since this api will be called directly by user. Is this a right way to do it? Moreover what would be returned exactly since response is passed through res and not return.

Advertisement

Answer

Good question,

The route handlers are just middlewares inside express architecture, and res.json({}) just passes data to the default middleware, so the return statement is used to stop the execution if there are other blocks of code below:

app.get("/", (req, res) => {
  if (something) {
     return res.json({ message: "A thing" });
  }

  res.json({ message: "Other thing" });
});
Advertisement