Mohammed
Mohammed

Reputation: 343

How to force end Response() ExpressJS , In easy way? (NodeJS)

How can I achieve this. In an easy way in ExpressJS?

App.get("/", async (req, res, next) => {
  await something.catch(err => {
    res.status(500).json("something wrong")
  })

  if (res.headersSent) return;
  res.json("2st response");
});

Can I just call res.json() two time then express automatically understand to end response and not to send second response ? without of using middleware to check that response already send or not!

Upvotes: 1

Views: 723

Answers (2)

jfriend00
jfriend00

Reputation: 707158

In your logic here with await, it's easier to just use try/catch instead of .catch() and that makes the flow a lot easier:

App.get("/", async (req, res, next) => {
  try {
      await something;
  } catch(err) {
      res.status(500).json("something wrong");
      return;
  });

  res.json("2st response");
});

In general, you don't mix await with .catch() and partly for this reason because using await and try/catch makes code flow like this simpler since you directly return from the outer function in the try/catch(err) statement, but you cannot do that in the .catch() statement.

Upvotes: 1

Sagi Rika
Sagi Rika

Reputation: 2979

You can use return before res.send. This way it will send a response and exit the function.

app.get("/", (req, res, next) => {
  return res.send("1st responce");

  // Unreachable code
  if(res.headersSent) return;
  res.json("2st responce")
})

Upvotes: 0

Related Questions