How can I get the status code from an http error in Axios?

前端 未结 10 1920
南旧
南旧 2020-11-28 02:27

This may seem stupid, but I\'m trying to get the error data when a request fails in Axios.

axios.get(\'foo.com\')
    .then((response) => {})
    .catch((         


        
相关标签:
10条回答
  • 2020-11-28 02:53

    You can use the spread operator (...) to force it into a new object like this:

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

    Be aware: this will not be an instance of Error.

    0 讨论(0)
  • 2020-11-28 02:54

    As @Nick said, the results you see when you console.log a JavaScript Error object depend on the exact implementation of console.log, which varies and (imo) makes checking errors incredibly annoying.

    If you'd like to see the full Error object and all the information it carries bypassing the toString() method, you could just use JSON.stringify:

    axios.get('/foo')
      .catch(function (error) {
        console.log(JSON.stringify(error))
      });
    
    0 讨论(0)
  • 2020-11-28 02:57

    This is a known bug, try to use "axios": "0.13.1"

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

    I had the same problem so I ended up using "axios": "0.12.0". It works fine for me.

    0 讨论(0)
  • 2020-11-28 02:59

    What you see is the string returned by the toString method of the error object. (error is not a string.)

    If a response has been received from the server, the error object will contain the response property:

    axios.get('/foo')
      .catch(function (error) {
        if (error.response) {
          console.log(error.response.data);
          console.log(error.response.status);
          console.log(error.response.headers);
        }
      });
    
    0 讨论(0)
提交回复
热议问题