我无法通过身份验证并获得响应,但是我分别使用了甜蜜警报来显示,但是在两种情况下都显示了一个甜蜜警报(即,错误一个甜蜜警报)。我也收到了“ error.response没有定义”。请帮忙。
export const authlogin = (email, password) =>{
return dispatch => {
dispatch(authStart());
axios.post('http://172.61.24.51:8050/api/user/login/', {
email: email,
password: password
}).then(res => {
const token = res.data.token;
if (token) {
dispatch(authEnd());
swal({
title: "Logged in!",
text: "Welcome back again. We missing you.",
icon: "success",
timer: 5000,
button: false
})
console.log(token);
const expirationDate = new Date(new Date().getTime() + 3600 * 1000);
localStorage.setTime('expirationDate', expirationDate);
dispatch(authSuccess(token));
dispatch(checkAuthTimeout(3600));
}
})
.catch(function(error) {
if (error) {
dispatch(authFail(error));
swal({
title: "Not logged in!",
text: "This is not you account?",
icon: "error",
timer: 2000,
button: false
})
}
});
// .catch (err => {
// dispatch(authFail(err))
// })
}
}
答案 0 :(得分:0)
我想显示第一个警报是因为,如果then()
回调中存在某种错误,它将被catch()
回调捕获。
因此,例如,如果您这里的属性为空或缺失,const token = res.data.token;
将导致捕获被调用。
同样,出于类似原因或某些CORS浏览器限制,也可能导致消息error.response is not defined
。
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);
});