如果长时间(处于待处理)状态,是否可以强制API调用失败?

时间:2018-12-24 17:37:36

标签: javascript axios fetch-api

这里我正在创建一个发布请求,并且我想触发该请求的状态,如果在(待定)状态下花费了一段特定的时间,迫使它失败,那有可能吗?

    fetch('http://localhost:5000/api', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        message: this.state.input,
      })
    })

我也在寻找使用axios的方式,而不仅仅是Fetch API。

1 个答案:

答案 0 :(得分:1)

http协议支持超时,您可以在axios中使用以下配置来设置请求的超时配置

axios({
  method: "post",
  url: 'http://example.com/api',
  timeout: 1000 * 5, // Wait for 5 seconds
  headers: {
    "Content-Type": "application/json"
  },
  data: {
    id: 1234
  }
})
  .then(response => {
    const serverResponse = response.data;
  })
  .catch(error => {
//    catch block with be executed if response take more than 5 seconds
    console.log(error);
});