API/JSON: 无法验证 CSRF 令牌的真实性

API/JSON: Can't verify CSRF token authenticity

我正在尝试为我的 Rails 应用程序构建一个 JSON API,并编写了以下方法:

  def create
    organization = Organization.find(params[:organization][:node_id])
    node = organization.nodes.build(nodes_params.except[:id])
    if node.save
      render json: node, status: :ok
    else
      render json: node, status: :bad_request
    end
  end

尝试 Postman 中的方法 returns 错误:"Can't verify CSRF token authenticity"。基于 this post 我将下面的代码添加到基本控制器中。不幸的是,这没有任何区别。有谁知道错误的原因吗?

protect_from_forgery
skip_before_action :verify_authenticity_token, if: :json_request?
private
  def json_request?
    request.format.json?
  end

根据对 application_controller.rb 的评论,您需要添加这一行 protect_from_forgery with: :null_session.

最好为继承自ApplicationController的所有API的控制器多做一个根控制器。即

class Api::ApiController < ApplicationController
  #TODO
  protect_from_forgery with: :null_session
end

其他API的控制器

class Api::V1::AddressesController < Api::ApiController
  #TODO
end

此控制器 class 可以帮助您仅对 API 的根而不是整个应用程序进行更改。您还可以使用此控制器在 API 的各种版本之间进行 D.R.Y 操作。