这可能看起来很愚蠢,但我试图在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'}

当前回答

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

此外,您还可以向这两种类型传递一个参数,以告知您所期望的内部响应。数据如下:

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

其他回答

与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(...).catch( error => { return Promise.reject(error.response.data.error); });

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

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
  });

};

看看控制台日志,你就明白了

整个错误只能用error来显示。这样的回答:

axios.get('url').catch((error) => {
      if (error.response) {
        console.log(error.response);
      }
    });

为了获得从服务器返回的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