React Native中的Fetch()API失败-“未处理的承诺被拒绝”

时间:2019-02-04 02:10:49

标签: javascript react-native fetch

我试图在本机反应中使用Fetch api,但出现一些问题。每当我尝试进行POST时,都会出现“未处理的承诺拒绝”错误,提示该正文不允许进行GET或HEAD重新请求。

GET方法可以很好地工作,只需在POST中使用即可。

有什么想法吗?

submit_task() {
    this.setModalVisible(!this.state.modalVisible);
    const task = {
        text: this.state.content,
        date: this.state.date
    }
    console.log(task);

    const API_URL = 'http://localhost:5000/tasks';
    fetch(API_URL, {
        methood: 'POST',
        body: JSON.stringify(task),
        headers: {
            'Content-Type': 'application-json',
        }
    })
}

2 个答案:

答案 0 :(得分:0)

您的提取选项中有一个错字methood应该是method。对于该问题,建议catch来自Promises的错误,例如:

submit_task() {
    this.setModalVisible(!this.state.modalVisible);

    const task = {
        text: this.state.content,
        date: this.state.date
    }

    const API_URL = 'http://localhost:5000/tasks';
    fetch(API_URL, {
        method: 'POST',
        body: JSON.stringify(task),
        headers: {
            'Content-Type': 'application-json',
        }
    }).catch(error => {
      // Maybe present some error/failure UI to the user here
    });
}

答案 1 :(得分:0)

此错误是由于您未在API调用中使用.catch这样处理您的异常

submit_task() {
    this.setModalVisible(!this.state.modalVisible);
    const task = {
        text: this.state.content,
        date: this.state.date
    }
    console.log(task);

    const API_URL = 'http://localhost:5000/tasks';
    fetch(API_URL, {
        methood: 'POST',
        body: JSON.stringify(task),
        headers: {
            'Content-Type': 'application-json',
        }
    })
.catch(error => {
      console.log('found error', error)
    });
    }

或在try中使用api调用并使用catch函数来处理异常或错误。

  try {
    submit_task() {
    this.setModalVisible(!this.state.modalVisible);
    const task = {
        text: this.state.content,
        date: this.state.date
    }
    console.log(task);

    const API_URL = 'http://localhost:5000/tasks';
    fetch(API_URL, {
        methood: 'POST',
        body: JSON.stringify(task),
        headers: {
            'Content-Type': 'application-json',
        }
    })
}
}
  catch(e){
   console.log('found error', error)
}