首页 > 解决方案 > 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 

标签: vue.jsdjango-rest-frameworkaxios

解决方案


如果其他人也有同样的问题:使用 axios,可以通过.catch(error => { console.log(error.response.data) }.


推荐阅读