【问题标题】:Retrieve response errors with axioson 400 and 401 status code使用 axioson 400 和 401 状态码检索响应错误
【发布时间】:2021-03-04 06:51:15
【问题描述】:

我正在尝试使用 axios 进行身份验证,但是什么时候出现错误 400 或 401,在缺少或错误的电子邮件和密码的情况下,我无法从 API 获得响应消息,控制台日志记录 axios 错误只显示这个:

error => 错误:请求失败,状态码为 400 在 createError (1.chunk.js:104463) 在解决(1.chunk.js:104697) 在 XMLHttpRequest.handleLoad (1.chunk.js:103940)

不知道如何获得正确的响应,即: {"errors":[{"message":"请提供邮箱和密码。"}]}

这是我的代码

(...)

axios.post('some api for authentication',
        {
            email: formData.email,
            password: formData.password,
            remember: formData.remember
        })
        .then(response => {
          token = response.data.session.user
          console.log('response =>', token)
        })
        .catch((error) => {
          token = null
          console.log('error =>', error)
        })

(...)

谢谢

【问题讨论】:

  • 您是否尝试过转换您发送 JSON 和测试的对象?
  • 你能给我们看一些后端代码吗?
  • 您分享了一个错误{"errors":[{"message":"Please supply e-mail and password."}]}errors 是什么类型?该类型的哪个元素有错误?该元素上的哪个属性具有错误消息字符串?问题是访问/查找数组中的元素吗?
  • 我不知道@AlexanderStaroselsky,因为我没有在 axios 中发现错误,我可以在 chrome devtools 中看到这个作为请求的响应。我的问题是我无法在axios“catch”的错误对象中得到这个消息
  • 查看 axios 文档,它有一个关于处理 errors 的部分。尝试在catch 中记录console.log(error.response.data);

标签: javascript reactjs axios


【解决方案1】:

根据 axios handling errorsmessage 等底层错误数据应可在 error.response.data 获得:

.catch((error) => {
  token = null
  console.log('error =>', error.response.data)
});

您可能希望使用该示例并处理可能发生的不同类型的错误:

.catch(function (error) {
  if (error.response) {
    // The request was made and the server responded with a status code
    // that falls out of the range of 2xx
    console.log(error.response.data);
    console.log(error.response.status);
    console.log(error.response.headers);
  } else if (error.request) {
    // The request was made but no response was received
    // `error.request` is an instance of XMLHttpRequest in the browser and an instance of
    // http.ClientRequest in node.js
    console.log(error.request);
  } else {
    // Something happened in setting up the request that triggered an Error
    console.log('Error', error.message);
  }
    console.log(error.config);
});

希望对您有所帮助!

【讨论】:

    猜你喜欢
    • 2023-03-19
    • 1970-01-01
    • 1970-01-01
    • 2021-04-02
    • 2019-02-16
    • 2018-11-07
    • 1970-01-01
    • 2020-07-09
    • 2018-06-10
    相关资源
    最近更新 更多