0

I am posting form data to an api using reactjs, I am trying to find out the response so I can put some error handling on my fetch function. My response is as follows, but it is 200:

{}

So how would I put this in a response code?

My submit function is:

handleSubmit(e) {
    e.preventDefault();
  /*global fetch */
    this.setState({ loading: true});
    fetch('https://bac1eal279.execute-api.eu-west-2.amazonaws.com/dev',{
        method: "POST",
        body: JSON.stringify(this.state),
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json',
        },
      }).then(
        (response) => (response.json())
       ).then((response)=>{       
    });
  }
Sole
  • 3,100
  • 14
  • 58
  • 112
  • I don't quite get your question. If your know you have a 200 response, even it's an empty JSON, you could put whatever response you what to show to users. – Colin Apr 26 '20 at 01:50
  • for example I have tried: `if (response.status === 200){ alert("Message Sent."); this.resetForm(); }else alert("Message failed to send."); }` which does not work? – Sole Apr 26 '20 at 01:52
  • Based on this response – Sole Apr 26 '20 at 01:53
  • Did you use response.status after you response.json()? Or before? check response.status first, if you it's 200 process data with response.json(), otherwise, pop error message – Colin Apr 26 '20 at 02:03
  • Do you have a code snippet? – Sole Apr 26 '20 at 02:15
  • check reponse status before json(). status is response property, json() is body method. https://stackoverflow.com/questions/38235715/fetch-reject-promise-and-catch-the-error-if-status-is-not-ok – Colin Apr 26 '20 at 02:20

2 Answers2

1

Fetch promises only reject with a TypeError when a network error occurs. Since 4xx and 5xx responses aren't network errors, there's nothing to catch. You'll need to throw an error yourself to use Promise#catch.

here you can check the status of the response object:

handleSubmit(e) {
   e.preventDefault();
   /*global fetch */
   this.setState({ loading: true});
   fetch('https://bac1eal279.execute-api.eu-west-2.amazonaws.com/dev',{
      method: "POST",
      body: JSON.stringify(this.state),
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
      },
   }).then((response) => {
    if (response.status === 200) {
       return response.json();
    } else {
      throw new Error('Something went wrong');
    }
  })
  .then((responseJson) => {
    // Do something with the response
  })
  .catch((error) => {
     console.log(error)
  });
}
Sachin
  • 911
  • 8
  • 12
0

You are not returning anything from your fetch. Cuz your 2nd .then is empty.

handleSubmit(e) {
    e.preventDefault();
  /*global fetch */
    this.setState({ loading: true});
    fetch('https://bac1eal279.execute-api.eu-west-2.amazonaws.com/dev',{
        method: "POST",
        body: JSON.stringify(this.state),
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json',
        },
      }).then(
        (response) => (response.json())
       ).then((response)=>{ 
            alert("Message Sent.");
            this.resetForm();
            return response; })
       .catch((e)=> {
            alert("ERROR");
            console.log(e);
       })
  }
Kid
  • 1,160
  • 2
  • 14
  • 31
  • Where would I add a conditional statement for send or error catching as follows: `if (response.status === 200){ alert("Message Sent."); this.resetForm(); }else alert("Message failed to send."); }` – Sole Apr 26 '20 at 02:19
  • The Promise returned from fetch() won’t reject on HTTP error status even if the response is an HTTP 404 or 500. Instead, it will resolve normally (with ok status set to false), and it will only reject on network failure or if anything prevented the request from completing. – Colin Apr 26 '20 at 02:23
  • strange thing is both alerts trigger? – Sole Apr 26 '20 at 02:23