如何从 Axios 中的 HTTP 错误中获取状态码?

新手上路,请多包涵

这可能看起来很愚蠢,但是当 Axios 中的请求失败时,我正在尝试获取错误数据。

axios
  .get('foo.example')
  .then((response) => {})
  .catch((error) => {
    console.log(error); //Logs a string: Error: Request failed with status code 404
  });

除了字符串,是否有可能获得一个可能包含状态代码和内容的对象?例如:

Object = {status: 404, reason: 'Not found', body: '404 Not found'}

原文由 Sebastian Olsen 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.1k
2 个回答

你看到的是 error 对象的 toString 方法返回的字符串。 ( error 不是字符串。)

如果从服务器接收到响应,则 error 对象将包含 response 属性:

 axios.get('/foo')
 .catch(function (error) {
 if (error.response) {
 console.log(error.response.data);
 console.log(error.response.status);
 console.log(error.response.headers);
 }
 });

原文由 Nick Uraltsev 发布,翻译遵循 CC BY-SA 3.0 许可协议

使用 TypeScript,很容易找到你想要的正确类型。

这使一切变得更容易,因为您可以获得具有自动完成功能的类型的所有属性,因此您可以知道响应和错误的正确结构。

 import { AxiosResponse, AxiosError } from 'axios'

axios.get('foo.example')
  .then((response: AxiosResponse) => {
    // Handle response
  })
  .catch((reason: AxiosError) => {
    if (reason.response!.status === 400) {
      // Handle 400
    } else {
      // Handle else
    }
    console.log(reason.message)
  })

此外,您可以将参数传递给这两种类型,以告诉您在内部期望什么 response.data 如下所示:

 import { AxiosResponse, AxiosError } from 'axios'
axios.get('foo.example')
  .then((response: AxiosResponse<{user:{name:string}}>) => {
    // Handle response
  })
  .catch((reason: AxiosError<{additionalInfo:string}>) => {
    if (reason.response!.status === 400) {
      // Handle 400
    } else {
      // Handle else
    }
    console.log(reason.message)
  })

原文由 Yan QiDong 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题