首页 > 解决方案 > axios 请求,从错误对象中读取验证消息

问题描述

发送 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,
    })
  }

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

标签: reactjsaxios

解决方案


您想要的详细信息在error.response.data

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

推荐阅读