vue.js - Django rest 框架在 400 Bad request 期间从响应中获取错误消息
问题描述
我目前正在运行一个 Vue + DRF 应用程序。当表单中的某些内容不符合标准并发送到 API 时,它会按预期返回 400 Bad request。检查“网络”选项卡中的响应,您会收到一条清晰的验证错误消息,例如{"zip_code":["This field must not be blank"]}
.
问题是,我如何提取它并将其显示在我的 Vue 应用程序中?试图捕捉错误只是返回Uncaught (in promise) Error: Request failed with status code 400 at eval
而不是实际的错误消息(“此字段不能为空”)。
代码修补看起来像:
axios.patch(`users/${this.$route.params.id}/`, this.user)
.then(...)
.catch(error => {...}) // get error message and display it frontend to user
解决方案
如果其他人也有同样的问题:使用 axios,可以通过.catch(error => { console.log(error.response.data) }
.
推荐阅读
- python - 在 3D 数据上使用 Standardscaler
- php - 从自定义分类中删除 foreach 循环中的重复项
- git - 必须区分詹金斯工作中的分支和标签
- google-app-engine - 如何修复 Go 1.11 模块未知导入路径,找不到模块提供包?
- dart - 颤振防止 Snackbar 在滑动时被解雇
- flutter - 警报对话框中的错误
- vb.net - 当表单调整大小时,如何移动覆盖在图片框上的标签
- python - 将 Fernet 密钥写入文本文件会生成字节字符串而不是 ASCII 字符串
- rest - 我需要对 Restapi 应用程序中的 Get 请求进行 csrf 保护吗?
- retrofit - 来自 Authenticator Okhttp3 的身份验证有 200 个响应代码,但它一直在调用直到消息太多后续请求:21