axios获取html页面,【Vue】axios如何获取后端接口返回的状态码以及相关信息

在Vue项目中,使用axios获取后端接口时,可以通过error.response.status判断状态码来处理错误信息。例如,当status为400或500时,可以输出相应错误信息。错误响应的结构一般包含status、error等字段。建议后端返回一个统一格式的错误信息,如包裹在200状态码内的data字段,以便前端进行错误处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

如题: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返回的是这个:

7603ee05764e843c3c93b595dbad0bd3.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"

}

回答

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);

});

返回值 res 就是包含 status 的对象, 直接使用if(res.status === 400)就是了。

{

"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"

}

error.response.status 就是了

常规的HTTP状态码本身有意义

2XX:请求成功

3XX:重定向

4XX:客户端错误

5XX:服务器端错误

根据问题并结合自身工作开发经验,我觉得题主可能需要一个封装过的返回结果,简单来说就是除了通信问题外的自定义错误情况(比如问题中的400 —— 手机号已存在)放在一个data字段中,然后包在200的http码中返回给到前端

{

code: 200,

data: {

timestamp: '',

status: 400,

errorMessage: '手机号已存在'

// ...

}

}

类似于这种格式的返回结果,当然这只是一种思路。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值