【问题标题】:axios request, reading validation message from error objectaxios 请求,从错误对象中读取验证信息
【发布时间】:2021-05-13 16:34:26
【问题描述】:

发送 axios put 请求并获取状态码 400 错误。

服务器发送用户友好的验证错误消息 它看起来像在开发工具中:

在 catch 块中,我希望收到带有 error.message 的消息,但这等于 Request failed with status code 400

  try {
    dispatch({
      type: SETTINGS_ALERT,
    })
    const response = await axios.put(
      `/author/me`,
      {
        data: {
          DisplayName: displayName,
          Description: description,
        },
      }
    )
    dispatch({
      type: SETTINGS_UPDATE_PROFILE_SUCCESS,
      payload: response.data,
    })
  } catch (error) {
//need to handle it here, bu error.message not works
    dispatch({
      type: SETTINGS_LOAD_FAIL,
      error: error.message,
    })
  }

我怎样才能正确阅读这条消息??

【问题讨论】:

  • 先尝试使用console.log(String(error)。看看会发生什么。
  • 我认为 error.response.data 是你要找的

标签: reactjs axios


【解决方案1】:

你要的详细信息在error.response.data:

dispatch({
      type: SETTINGS_LOAD_FAIL,
      error: error.response.data,
    })

【讨论】:

    猜你喜欢
    • 2022-11-01
    • 1970-01-01
    • 2012-05-22
    • 2023-01-14
    • 2021-01-13
    • 2015-05-10
    • 1970-01-01
    • 2017-04-02
    • 1970-01-01
    相关资源
    最近更新 更多