3

如题:axios如何获取后端接口返回的状态码以及相关信息

axios返回的有两个函数

axios.get("/internal/user/check_mobile_and_sent_code",{withCredentials:true,params:{mobile:formInline.mobile}}).then(res=>{
                        console.log(res);
                        //if(res.result==true){
                            if (!this.timer) {
                                this.count = this.TIME_COUNT;
                                this.show = false;
                                this.timer = setInterval(() => {
                                    if (this.count > 0 && this.count <= this.TIME_COUNT) {
                                        this.count--;
                                    } else {
                                        this.show = true;
                                        clearInterval(this.timer);
                                        this.timer = null;
                                    }
                                }, 1000)
                            }
                        //}
                    }).catch(error=>{
                        console.log(error);
                    })

我想判断当 返回400或者500的时候 输出相应的返回信息,请问大神们该怎么判断呀?
console.log(error);这个error返回的是这个:

clipboard.png

而后台实际返回的是这个:

{
  "timestamp": "2017-09-15T08:30:56Z",
  "status": 400,
  "error": "Bad Request",
  "exception": "com.xinwenhd.common.utils.BadReqExcption",
  "message": "Bad Request",
  "path": "/internal/user/check_mobile_and_sent_code",
  "errorMassage": "手机号已存在",
  "errorCode": "MOBILE_EXIST"
}
2017-09-15 提问

查看全部 4 个回答

11

已采纳
axios.get('/user/12345')
  .catch(function (error) {
    if (error.response) {
      // The request was made and the server responded with a status code
      // that falls out of the range of 2xx
      console.log(error.response.data);
      console.log(error.response.status);
      console.log(error.response.headers);
    } else if (error.request) {
      // The request was made but no response was received
      // `error.request` is an instance of XMLHttpRequest in the browser and an instance of
      // http.ClientRequest in node.js
      console.log(error.request);
    } else {
      // Something happened in setting up the request that triggered an Error
      console.log('Error', error.message);
    }
    console.log(error.config);
  });

Handling Errors https://github.com/mzabriskie...

推广链接