无法处理401个错误



当我从后端发送res.status(401(.send("身份验证错误"(,并试图在react前端捕获它时,我无法检查错误的状态。即使错误代码为401,它也总是无法传递if语句。我该如何解决这个问题,以便当状态为401时,它通过if语句?

onSubmit = async (e) => {
let formData = new FormData();
formData.append('image', this.state.file);
try {
const res = await axios({
method: 'post',
url: '/api/search',
data: formData,
headers: {'Content-Type': 'multipart/form-data' }
})
} catch (err) {
// authentication required 
if (err['status'] === 401) {
console.log('authentication problems');
this.props.history.push('/');
};
}
}

使用err.response.status === 401err['response']['status'] === 401而不是err['status'] === 401

最新更新