【问题标题】:Get Axios frontend Promise to receive errors msg from Rails backend获取 Axios 前端 Promise 以接收来自 Rails 后端的错误消息
【发布时间】:2018-05-23 07:24:26
【问题描述】:

我要在 Rails 中返回:

render json: { errors: e.response.body.errors }, status: 400

在 JavaScript 中我使用的是 Axios:

axios.patch('/settings/account', {}, {params: {...
    } })
  .then((e)=> {
    ...
    console.log('submitted')
  })
  .catch(function (error, res) {
    // only get error that gives 400, but not error msg here, res isn't here
    console.log(error);
  });

如何在我的前端获取e.response.body.errors

【问题讨论】:

    标签: javascript ruby-on-rails error-handling promise axios


    【解决方案1】:

    如果服务器响应 http 状态码不是 2xx,Axios 会拒绝承诺。我看到您正在从服务器发送错误响应,但是您是通过 http 错误状态发送此响应吗?如果你不是,则该错误不是 axios 的错误,因此该错误将显示在“then()”钩子中,因为 promise 已解决。

    如果是,那么您应该会看到 error.response.data 的错误

    【讨论】:

    • 如果您的服务器返回 2xx 以外的任何内容,Axios 首先会捕获错误。如果错误有响应正文,您应该在error.response.data 中看到正文。但是 axios 可能会捕获其他错误,例如您的服务器在发送此错误正文时遇到任何问题。如果发生这种情况,您应该会看到错误 whitin error.messageerror.request 或只是 console.log(error) 看看发生了什么。
    猜你喜欢
    • 2021-07-27
    • 1970-01-01
    • 1970-01-01
    • 2022-06-22
    • 2017-08-26
    • 2020-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多