0

I have a simple express app with handler (just for demonstration it's just sending error with status code 400):

router.post('/createUser', cors() as RequestHandler, async (req, res, next) => {
  return res.status(400).json('Something went wrong');
});

I also tried res.status(400).send('Something went wrong');, but it's being sent as HTML.

Tried res.status(400).send(new Error('Something went wrong'));, it's not being caught, and the response is {}.

When I call the endpoint:

fetch(`${url}/createUser`)
.then(res => {
  // this block gets invoked
}).catch(e => {
  // instead of this
})

How to send the response with express, so the above issue gets solved?

Gergő Horváth
  • 3,195
  • 4
  • 28
  • 64
  • Does this answer your question? [Fetch: reject promise and catch the error if status is not OK?](https://stackoverflow.com/questions/38235715/fetch-reject-promise-and-catch-the-error-if-status-is-not-ok) – David Feb 21 '23 at 19:54
  • I was expecting that there is a way in express to do this, and don't have to create middlewares on the caller's side to translate responses with 4xx 5xx status codes to errors – Gergő Horváth Feb 21 '23 at 19:58
  • Then you may be looking to use something like Axios instead of `fetch`. – David Feb 21 '23 at 19:59

0 Answers0