繁体   English   中英

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

[英]How can I get the status code from an HTTP error in Axios?

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

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

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

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

你看到的是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);
    }
  });

使用 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)
  })

正如@Nick 所说,您在console.log一个 JavaScript Error对象时看到的结果取决于console.log的确切实现,这会有所不同并且(imo)使检查错误非常烦人。

如果您想查看完整的Error对象以及绕过toString()方法携带的所有信息,您可以使用JSON.stringify

axios.get('/foo')
  .catch(function (error) {
    console.log(JSON.stringify(error))
  });

请求配置中有一个名为validateStatus的新选项。 您可以使用它来指定当状态 < 100 或状态 > 300(默认行为)时不引发异常。 例子:

const {status} = axios.get('foo.example', {validateStatus: () => true})

您可以使用扩展运算符 ( ... ) 将其强制转换为这样的新对象:

axios.get('foo.example')
    .then((response) => {})
    .catch((error) => {
        console.log({...error})
})

请注意:这不会是 Error 的实例。

我正在使用这个拦截器来获取错误响应。

const HttpClient = axios.create({
  baseURL: env.baseUrl,
});

HttpClient.interceptors.response.use((response) => {
  return response;
}, (error) => {
  return Promise.resolve({ error });
});

为了获取服务器返回的http状态码,可以在axios选项中添加validateStatus: status => true

axios({
    method: 'POST',
    url: 'http://localhost:3001/users/login',
    data: { username, password },
    validateStatus: () => true
}).then(res => {
    console.log(res.status);
});

这样,每个 http 响应都会解析从 axios 返回的承诺。

https://github.com/axios/axios#handling-errors

整个错误只能使用 error.response 来显示:

axios.get('url').catch((error) => {
      if (error.response) {
        console.log(error.response);
      }
    });
const handleSubmit = (e) => {
e.preventDefault();
// console.log(name);
setLoading(true);
createCategory({ name }, user.token)
  .then((res) => {
   // console.log("res",res);
    setLoading(false);
    setName("");
    toast.success(`"${res.data.name}" is created`);
    loadCategories();
  })
  .catch((err) => {
    console.log(err);
    setLoading(false);
    if (err.response.status === 400) toast.error(err.response.data);//explained in GD
  });

};

看控制台日志你就明白了

在此处输入图像描述

使用 Axios

    post('/stores', body).then((res) => {

        notifyInfo("Store Created Successfully")
        GetStore()
    }).catch(function (error) {

        if (error.status === 409) {
            notifyError("Duplicate Location ID, Please Add another one")
        } else {
            notifyError(error.data.detail)
        }

    })

您可以将错误放入一个对象并记录该对象,如下所示:

axios.get('foo.example')
    .then((response) => {})
    .catch((error) => {
        console.log({error}) // this will log an empty object with an error property
    });

仅获取错误不返回对象确实很奇怪。 在返回error.response 时,您可以访问所需的大多数反馈信息。

我最终使用了这个:

axios.get(...).catch( error => { return Promise.reject(error.response.data.error); });

这严格提供了我需要的东西:状态代码(404)和错误的文本消息。

这是一个已知的错误,尝试使用"axios": "0.13.1"

https://github.com/mzabriskie/axios/issues/378

我遇到了同样的问题,所以我最终使用了"axios": "0.12.0" 这对我来说可以。

Axios. get('foo.example')
.then((response) => {})
.catch((error) => {
    if(error. response){
       console.log(error. response. data)
       console.log(error. response. status);

      }
})

这是我的代码:为我工作

 var jsonData = request.body;
    var jsonParsed = JSON.parse(JSON.stringify(jsonData));

    // message_body = {
    //   "phone": "5511995001920",
    //   "body": "WhatsApp API on chat-api.com works good"
    // }

    axios.post(whatsapp_url, jsonParsed,validateStatus = true)
    .then((res) => {
      // console.log(`statusCode: ${res.statusCode}`)

            console.log(res.data)
        console.log(res.status);

        // var jsonData = res.body;
        // var jsonParsed = JSON.parse(JSON.stringify(jsonData));

        response.json("ok")
    })
    .catch((error) => {
      console.error(error)
        response.json("error")
    })

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM