如果用户已经存在,如何处理Axios帖子上vue js中的验证失败422错误



Vue控制台错误日志

在尝试使用Laravel和Vue资源执行POST请求时,我收到了这个422(不可处理实体(错误。我目前有以下代码:

register() {
this.loading = true;          
this.axios.post('register', {
firstname: this.firstname,
lastname: this.lastname,
email: this.email,
password: this.password,
password_confirmation: this.password_confirmation
})
.then(response => {
this.loading = false;
this.name = '';
this.email = '';
this.password = '';
this.password_confirmation = '';
this.loginUser(response);
})
.catch(err => {
this.loading = false;            
if(err.response && err.response.data &&  err.response.data.errors){
this.errors = err.response.data.errors;
console.log(err.response.data.errors);
}

});
}

这是我如何在catch((方法中处理它的示例

.catch(function(err){
if(err.response.status == 422) {
$.each(err.response.data.errors, function(key, value) {
if(key == 'email'){
view.emailError = err.response.data.errors.email[0]; //NB: emailError is registered in Vue data 
}
if(key == 'password'){
view.passwordError = err.response.data.errors.password[0]; //NB: passwordError is registered in Vue data 
}
});
}
});

你需要在Vue数据中注册一个元素来保存错误,就像我一样"emailError";以及";passwordError";也可以像$('#emailErrorHolder').text(err.response.data.errors.email[0])一样直接更新元素;

最新更新