【问题标题】:How to catch status = cancelled in axios?如何在axios中捕获状态=取消?
【发布时间】:2016-08-04 03:46:34
【问题描述】:

我目前正在运行 2 台服务器:

  1. 使用 react 为视图提供服务,该视图从使用 express 构建的 REST API 检索数据。
  2. 为视图提供 REST API。

以下是我登录用户的操作:

// Redux Action
export function loginUser(creds, role) {

  return dispatch => {
    // We dispatch requestLogin to kickoff the call to the API
    dispatch(requestLogin(creds));

    return axios.post(`${ROOT_URL}/login/${role}`, creds).then((response) => {
        console.log(response);

        if(response.status === 200) {
          // If login was successful, set the token in local storage
          localStorage.setItem('id_token', response.data);

          // Dispatch the success action
          dispatch(receiveLogin(response));

          return response;
        }
      }).catch(err => {
        // If there was a problem, we want to
        // dispatch the error condition
        dispatch(loginError(err.data));

        return err;
      });
  };
}

我故意断开我的数据库以捕获错误并查看会发生什么。所以,这就是我在终端中看到的:

12:49:24 Project-0 Server is listening at port 3000
12:49:24 Project-0 Mongoose disconnected
12:49:24 Project-0 Mongoose connection error: MongoError: connect ECONNREFUSED 192.168.1.116:27017
12:49:34 Project-0 Wed, 13 Apr 2016 07:19:34 GMT express deprecated res.send(status): Use res.sendStatus(status) instead at app/index.js:61:7
12:49:34 Project-0 OPTIONS /login/admin Wed, 13 Apr 2016 07:19:34 GMT ::ffff:192.168.1.134 200 5.894
12:49:35 Project-0 POST /login/admin Wed, 13 Apr 2016 07:19:35 GMT ::ffff:192.168.1.134 - -

现在,当我提交登录表单时,状态会从待处理变为已取消

我们如何使用 axios 捕捉这种状态,还是我们必须在 express 中为此编写一个机制?

Axios 0.10.0

注意:我无法标记 axios,因为该标记不存在并且我无法创建新的。

【问题讨论】:

  • 嗨,您现在在哪里看到状态(待定、已取消)?在您的情况下,这些状态意味着什么?你为什么取消它?从你的问题很难理解
  • @AlexBuduguru 我不确定它是否已在较新版本的 Axios 中修复。我已经提到它出现在 Axios 0.10.0 版本中。我在谷歌浏览器的网络标签中看到了状态。我已经解释过我断开了应用程序与数据库的连接。因此,发送请求并等待一段时间后,状态变为已取消。
  • 我想我不明白捕获状态类型的目的是什么以及您要解决什么问题。你能详细说明一下吗?问题是请求被取消了,你不明白为什么会这样,对吧?
  • 查看我们捕获的状态类型,以便我们可以记录错误/成功消息。如果状态是成功的,那么我们通常会使用数据。如果状态类型被取消或失败,我们需要记录它以进行调试或显示某些事情不顺利。因此我想捕获状态类型被取消,以便我可以记录一个 nessage。但不幸的是我没能抓住它。
  • 您可以将 console.log(err) 放在您的 catch 语句中 - 这将记录不成功的响应。为什么你还需要其他东西? .catch(err => { console.log(err)});

标签: ajax rest express redux axios


【解决方案1】:

使用 axios.isCancel()

.catch(err => { 
      if(axios.isCancel(err)) {
        // do something
      }
   }
)

【讨论】:

    【解决方案2】:

    您实际上在 catch 语句中捕获了错误(不成功的响应)。例如,您可以像这样将其记录到控制台:

    .catch(err => {
            // If there was a problem, we want to
            // dispatch the error condition
            dispatch(loginError(err.data));
            console.log(err);
            return err;
          });

    【讨论】:

      猜你喜欢
      • 2018-08-22
      • 1970-01-01
      • 2022-12-15
      • 1970-01-01
      • 2019-03-07
      • 2022-01-16
      • 2011-02-13
      相关资源
      最近更新 更多