0

In the below code, a 404 status is sent up to the front end causing the res.ok property to be false. Is there a way to have access to this message from the backend in the front end if statement where the res.ok value is checked?

app.post('/recover_password', (req, res) => {
  const customer_has_account = true

  if (!customer_has_account) {
    return res.status(404).json('no account found with that email')
  }
})
fetch('/recover_password', {
  method: 'POST',
  body: /* ... */
})
  .then(res => {
    if (!res.ok) {
      throw new Error(/* can error be passed in here somehow? */)
    }
    return res.json()
  })
  .then(data => console.log(data))
  .catch(err => {
    console.log(err)
  })

I suppose this would also work but I am wondering if there is a specific way to do this as shown above

app.post('/recover_password', (req, res) => {
  const customer_has_account = true

  if (!customer_has_account) {
    return res.status(404).json({ error: 'no account with that email found '})
  }
})

fetch('/recover_password', {
  method: 'POST',
  body: /* ... */
})
  .then(res => res.json())
  .then(data => {
    if (data.error) throw new Error(data.error)
  })
  .catch(err => console.log(err))
dbzx10299
  • 722
  • 2
  • 14
  • `throw new Error(await res.json())` – Bergi Feb 05 '23 at 18:39
  • Between the two examples I gave above is one better practice than the other? – dbzx10299 Feb 05 '23 at 18:41
  • 1
    The second one also rejects if you have a 200 success response that accidentally has a `.error` property. I would avoid that and make use of http status code if possible - particularly if you want a REST API. – Bergi Feb 05 '23 at 18:43

0 Answers0