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

当前回答

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

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

其他回答

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

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

我遇到了同样的问题,所以我最终使用了“axios”:“0.12.0”。这对我来说很有效。

正如@Nick所说,当你在console.log中设置一个JavaScript错误对象时,你所看到的结果取决于console.log的确切实现,这使得检查错误变得非常烦人。

如果你想看到完整的Error对象和它所携带的所有信息,绕过toString()方法,你可以使用JSON.stringify:

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

你可以把错误放入一个对象并记录该对象的日志,如下所示:

axios.get('foo.example')
    .then((response) => {})
    .catch((error) => {
        console.log({error}) // this will log an empty object with an error property
    });
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
  });

};

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

您看到的是错误对象的toString方法返回的字符串。(错误不是一个字符串。)

如果从服务器接收到响应,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);
    }
  });