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

前端 未结 10 1959
南旧
南旧 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: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)
      })
    

提交回复
热议问题