为什么Rails应该渲染422时渲染200?

时间:2020-05-18 08:05:18

标签: ruby-on-rails

这是我的控制器动作

  def create
    @book = Book.new(title: params[:title])
    if @book.save
      render json: @book.to_json
    else
      render json: {:errors => @book.errors.to_json}, status: 422
    end
  end

这是我的React代码

handleSubmit = (event) => {
    event.preventDefault();
    console.log('here')
    Axios.post(
        `${process.env.REACT_APP_API_URL}/books`,
        {
            title: this.state.title
        }
    ).then(response => {
        console.log(response);
    }).catch(error => {
        console.log(error)
    })
}

react代码中的正常响应块被调用。我看一下浏览器的JavaScript控制台,响应如下:

{data: {…}, status: 200, statusText: "OK", headers: {…}, config: {…}, …}


这是我在Rails控制台输出中看到的:

Started POST "/books" for 10.0.0.204 at 2020-05-18 07:59:46 +0000
Processing by BooksController#create as HTML
  Parameters: {"title"=>"asdf", "book"=>{"title"=>"asdf"}}
   (0.2ms)  BEGIN
  ↳ app/controllers/books_controller.rb:11
   (0.1ms)  ROLLBACK
  ↳ app/controllers/books_controller.rb:11
error
Completed 200 OK in 4ms (Views: 0.1ms | ActiveRecord: 0.3ms)

因此出于某种原因,它仍将状态设置为200。

2 个答案:

答案 0 :(得分:0)

我最终重写了代码,而不是

  def create
    @book = Book.new(title: params[:title])
    if @book.save
      render json: @book.to_json
    else
      render json: {:errors => @book.errors.to_json}, status: 422
    end
  end

我有

  def create
    @book = Book.create(title: params[:title])
    unless @book.errors
      render json: @book.to_json
    else
      puts @book.errors.inspect
      render status: 422, json: @book.errors.to_json
    end
  end

答案 1 :(得分:0)

您的操作似乎正在以HTML而不是JSON或 / 的形式进行处理。也许您需要将application / json添加到请求标头的内容类型中?