2

sirs. I am trying understand ExpressJS. I want to send simple object from express server but it just logs cannot get on screen.

app.get("/", (req, res, next) => {
  console.log("middleware");
  const error = true;

  if (error) {
    next();
  }
});

app.use((err, req, res, next) => {
  res.status(400).json({ error: "error description" });
});

In this code i simulated if error happens send object but it just sends cannot get. In POSTMAN body section, i just see html code with cannot get. What happening here? Can you please explain me?

In POSTMAN i can just get this HTML code.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <title>Error</title>
</head>

<body>
    <pre>Cannot GET /</pre>
</body>

</html>

1 Answer 1

1

The error handler is never reached, because there is no error passed to the next() function. Because the first route handler doesn´t send a response, you get 'Cannot GET /'.

From the Express docs:

For errors returned from asynchronous functions invoked by route handlers and middleware, you must pass them to the next() function, where Express will catch and process them.

Just pass the error to the next() function, and your code will work as expected. In your example:

app.get("/", (req, res, next) => {
  console.log("middleware");
  const error = new Error('bad things just happened');

  if (error) {
    next(error);
  }
});

app.use((err, req, res, next) => {
  res.status(400).json({ error: "error description" });
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.