Javascript 获取的Ajax请求状态代码标识

Javascript 获取的Ajax请求状态代码标识,javascript,ajax,reactjs,Javascript,Ajax,Reactjs,我正在使用reactjs将表单数据发布到api,我正在尝试找出响应,以便对我的fetch函数进行一些错误处理。我的答复如下,但是200: {} 那么我该如何将其放入响应代码中呢 我的提交功能是: handleSubmit(e) { e.preventDefault(); /*global fetch */ this.setState({ loading: true}); fetch('https://bac1eal279.execute-api.eu-west-2.

我正在使用reactjs将表单数据发布到api,我正在尝试找出响应,以便对我的fetch函数进行一些错误处理。我的答复如下,但是200:

{}
那么我该如何将其放入响应代码中呢

我的提交功能是:

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

你没有从你的取回中归还任何东西。因为你的第二个
。然后
是空的

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

当发生网络错误时,Fetch承诺仅拒绝TypeError。因为4xx和5xx响应不是网络错误,所以没有什么可捕获的。您需要自己抛出一个错误才能使用
Promise\catch

您可以在此处检查响应对象的状态:

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

我不太明白你的问题。如果您知道您有一个200响应,即使它是一个空的JSON,您也可以将您要向用户显示的任何响应放入其中。例如,我尝试过:
If(response.status==200){alert(“Message Sent”);this.resetForm();}else alert(“Message failed to send”);}哪个不起作用?基于此ResponseId,在response.json()之后使用response.status?还是以前?首先检查response.status,如果是200,则使用response.json()处理数据,否则,弹出错误消息您有代码段吗?我应该在哪里添加用于发送或错误捕获的条件语句,如下所示:
if(response.status==200){alert(“Message Sent”);this.resetForm();}else alert(“Message failed to send”);}从fetch()返回的承诺不会在HTTP错误状态下拒绝,即使响应是HTTP 404或500。相反,它将正常解析(ok status设置为false),并且它只会在网络故障或任何阻止请求完成的情况下拒绝。奇怪的是这两个警报都会触发吗?