从React JS中的Rails API获取错误文本

时间:2018-10-22 10:10:29

标签: ruby-on-rails reactjs promise

所以我正在使用React前端和Rails API后端。

当客户端尝试创建用户时,它可能会出现一些错误,我想显示这些错误。

但是,在下面的代码中,我只在控制台中得到错误代码,而不是文本:

Error: Request failed with status code 422

我处理API请求/响应的React代码:

signup(e) {
    e.preventDefault();
    axios.post( '/api/v1/users', { user })
    .then(response => {
      // here is the response, works great
    })
    .catch(error => {
        console.log(error) // this just output the 422 error in the console.
    })
  }

我的Rails UsersController中的Ruby代码:

    def create
      @user = User.new(user_params)
      if @user.save
        render json: @user, status: :created
      else
        render json: @user.errors, status: :unprocessable_entity
      end
    end

在控制台的网络响应中,我实际上正在获得期望的结果:

{"first_name":["can't be blank"],"phone_number":["is the wrong length (should be 10 characters)"]}

如何从错误捕获块中的console.log输出中获取上方的响应?

0 个答案:

没有答案