How do I show message on 403 client side if the email fails to send?

Viewed 342

I am trying to show alert message when the email sends or gets failed. If it fails, I'm getting 403 from the backend. But not sure how do I show it here in client-side. If success, I get a 200. Right now, in the case of failure, if I console.log(res)(as you can see below), it shows

res is not defined

Uncaught (in promise) Error: Request failed with status code 403

And in network tab, I get the response. That's alright.

I just want to show it here client side in my react component.

  handleClick = (id) => {
    axios
      .post(`http://localhost:3000/api/v1/users/send-post/${id}`)
      .then((res) =>
        console.log(res),
        res.status === 200 ? alert("Email sent"): null
      )
      .catch((err) => {
        if (err) {
          return alert("Sorry, Something went wrong")
        }
      })
    }
2 Answers

The error status is in err.response.status.

Modify

if (err) {
          return alert("Sorry, Something went wrong")
        }

with

if (err) {
          return alert("Sorry, Something went wrong. Status "+ err.response.status)
        }

For reference, you check this link https://stackoverflow.com/a/39153411/12680971

You have a comma , after console.log call.

Do next:

.then(res => {
   console.log(res);
   res.status === 200 && alert("Email sent");
})

Or another variant:

.then(res =>
   console.log(res) ||
   res.status === 200 ? alert("Email sent") : null
)
Related