当状态为400时,如何在axios中获取响应正文?

Lui*_*our 5 javascript reactjs axios

我正在开发一个应用程序,当用户发送无效或不完整的数据时,我想使用状态代码 400,但是当 axios 收到 400 状态代码时,它会抛出错误,我无法从中获得响应,它只是给出我收到一个包含请求但不包含响应的错误,我该如何处理?

const getIdTypes = () => {
  return axios_instance.get
    (idTypesUrl)
}


const getValidIdTypes = async () => {
  return infoActions.getIdTypes()
  .then(res => {
    if (res.status !== 200 && res.status !== 201) {
      pushToFlasher(res.data)
    }
    setValidIdTypes(res.data)
  })
  .catch(err => {
    if (err.request) {
      console.log("err:", err.request)
    }
     if (err.response) {
      console.log("err:", err.response)
    }
    // pushToFlasher(err.response.data)
  })
}


Run Code Online (Sandbox Code Playgroud)

Nik*_*zur 10

您可以在创建实例时指定哪些状态代码有效:

const instance = axios.create({
  baseURL: 'some api url',
  timeout: 1000 * 30,
  validateStatus: (status) => {
    return status >= 200 && status < 500
  },
})
Run Code Online (Sandbox Code Playgroud)

因此,这里 200 到 500 之间的所有状态都将被视为有效,不会抛出错误。

在你的情况下你可以return status === 400

  • 太感谢了,我差点拿砖头砸膝盖了。 (3认同)