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

前端 未结 10 1919
南旧
南旧 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:45

    There is a new option called validateStatus in request config. You can use it to specify to not throw exceptions if status < 100 or status > 300 (default behavior). Example:

    const {status} = axios.get('foo.com', {validateStatus: () => true})
    
    0 讨论(0)
  • 2020-11-28 02:47

    You can put the error into an object and log the object, like this:

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

    Hope this help someone out there.

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

    It's my code: Work for me

     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")
        })
    
    0 讨论(0)
  • 2020-11-28 02:49

    In order to get the http status code returned from the server, you can add validateStatus: status => true to axios options:

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

    This way, every http response resolves the promise returned from axios.

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

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

    I am using this interceptors to get the error response.

    const HttpClient = axios.create({
      baseURL: env.baseUrl,
    });
    
    HttpClient.interceptors.response.use((response) => {
      return response;
    }, (error) => {
      return Promise.resolve({ error });
    });
    
    0 讨论(0)
  • 2020-11-28 02:52

    With TypeScript, it is easy to find what you want with the right type.

    import { AxiosResponse, AxiosError } from 'axios'
    
    axios.get('foo.com')
      .then(response: AxiosResponse => {
        // Handle response
      })
      .catch((reason: AxiosError) => {
        if (reason.response!.status === 400) {
          // Handle 400
        } else {
          // Handle else
        }
        console.log(reason.message)
      })
    
    0 讨论(0)
提交回复
热议问题