【问题标题】:Django rest framework get error message from response during a 400 Bad requestDjango rest 框架在 400 Bad request 期间从响应中获取错误消息
【发布时间】:2020-11-17 23:13:20
【问题描述】:

我目前正在运行一个 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.js django-rest-framework axios


    【解决方案1】:

    如果其他人有同样的问题:使用axios,可以通过.catch(error => { console.log(error.response.data) }获取错误响应体。

    【讨论】:

      猜你喜欢
      • 2019-08-09
      • 2020-02-25
      • 2016-11-10
      • 1970-01-01
      • 1970-01-01
      • 2014-11-18
      • 2018-12-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多