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)=>{       
    });
  }
6
  • 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. Commented Apr 26, 2020 at 1: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? Commented Apr 26, 2020 at 1:52
  • Based on this response Commented Apr 26, 2020 at 1: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 Commented Apr 26, 2020 at 2:03
  • Do you have a code snippet? Commented Apr 26, 2020 at 2:15

2 Answers 2

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)
  });
}
Sign up to request clarification or add additional context in comments.

Comments

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);
       })
  }

3 Comments

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."); }
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.
strange thing is both alerts trigger?

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.