javascript - 处理 axios 错误和响应 (vue) 仅适用于一个错误。如何通知多个错误?
问题描述
我有一个与 API 通信(使用 axios 请求)并返回错误的 Vue 应用程序。如果我只收到一个错误,它就可以正常工作,例如当响应如下时:{"error":"passwords.token"}
当我收到这样的累积错误时:
{"message":"The given data was invalid.",
"errors":{
"password":["The password confirmation does not match."]}
}
这是我的 Vue 组件和方法 resetPassword() 的代码
methods: {
resetPassword () {
this.$vs.loading()
const payload = {
userDetails: {
email: this.email,
password: this.password,
password_confirmation: this.password_confirmation,
token: this.token
}
}
this.$store.dispatch('auth/resetPassword', payload)
.then((response) => {
this.$vs.loading.close()
this.$vs.notify({
time: 10000,
title: 'Authentication Success',
text: response.message.data.message,
iconPack: 'feather',
icon: 'icon-success-circle',
color: 'success'
})
})
.catch(error => {
this.$vs.loading.close()
this.$vs.notify({
time: 6000,
title: 'Authentication Error',
text: error.message,
iconPack: 'feather',
icon: 'icon-alert-circle',
color: 'danger'
})
})
},
},
解决方案
不要有不同的键,因为一次会是一个错误,而其他时候会是两个或三个。例如不要这样做:
1 错误:{错误:“错误消息”}
2 错误:{错误:{“错误_1”:“错误消息 1”} }
如您所见,这非常复杂。只需在其中放一个 syndax,然后即使它一两个左右也可以跟随它。例如你可以让它像
errors: [
{type: "wrong_user_name_or_password", message: "Wrong user name or password"}
]
然后您可以美化您的通知功能以循环所有错误并显示它们,例如
无法登录。原因:
推荐阅读
- apache-spark - why isnull() and .isNull in Pyspark 1.6 producing different results?
- angular - Angular Components inside ngfor card list
- nattable - NatTable allow cell editing only when cell is selected
- databricks - 从 Databricks 加载雪花会更改表结构
- ruby-on-rails - 遍历 ruby 中的数组
- google-apps-script - 输入代码时,有没有办法在单元格中返回值?
- c - 如何将 librdkafka 有效负载转换为 json 以获取参数值?
- reactjs - 如何将 jest.spyOn 与功能性反应组件一起使用
- asp.net-core - ASP.Net Core 网站每天同时阻塞
- angular - NodeJS如何将数据发送到一个特定的客户端