我正在开发一个应用程序,当用户发送无效或不完整的数据时,我想使用状态代码400,但是当axios接收到一个400状态代码时,它会抛出一个错误,而我无法从它得到响应,它只会给出一个包含请求而不是响应的错误,我应该如何处理这个问题呢?
const getIdTypes = () => {
return axios_instance.get
(idTypesUrl)
}
const getValidIdTypes = async () => {
return infoActions.getIdTypes()
.then(res => {
if (res.status !== 200 && res.status !== 201) {
pushToFlasher(res.data)
}
setValidIdTypes(res.data)
})
.catch(err => {
if (err.request) {
console.log("err:", err.request)
}
if (err.response) {
console.log("err:", err.response)
}
// pushToFlasher(err.response.data)
})
}
发布于 2021-09-10 15:44:32
在创建实例时,可以指定哪些状态代码是有效的:
const instance = axios.create({
baseURL: 'some api url',
timeout: 1000 * 30,
validateStatus: (status) => {
return status >= 200 && status < 500
},
})
因此,在这里,所有状态在200到500之间,都将被认为是有效的,并且不会抛出错误。
在您的例子中,您可以只使用return status === 400
发布于 2021-09-10 19:57:02
在catch块中,您可以通过获取err.response.data
对象访问服务器发送的错误响应:
const getValidIdTypes = async () => {
return infoActions.getIdTypes()
.then(res => {
if (res.status !== 200 && res.status !== 201) {
pushToFlasher(res.data)
}
setValidIdTypes(res.data)
})
.catch(err => {
console.log(err.response.data)
})
}
对于exmaple,如果服务器发送此对象:
{
status: 400,
message: "there is a problem"
}
您可以这样获得“消息”:err.response.data.message
https://stackoverflow.com/questions/69134688
复制相似问题