Ruby on rails API/JSON:Can';t验证CSRF令牌的真实性

Ruby on rails API/JSON:Can';t验证CSRF令牌的真实性,ruby-on-rails,ruby,api,ruby-on-rails-4,authenticity-token,Ruby On Rails,Ruby,Api,Ruby On Rails 4,Authenticity Token,我正在尝试为我的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

我正在尝试为我的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中尝试该方法会返回错误:“无法验证CSRF令牌的真实性”。基于此,我将下面的代码添加到基本控制器。不幸的是,这没有什么区别。有人知道错误的原因吗

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

根据
application\u controller.rb
上的注释,您需要将此行
使用::null\u会话保护\u免受伪造

如果您只为继承自
ApplicationController
的所有API控制器多创建一个根控制器,效果会更好。i、 e

class Api::ApiController < ApplicationController
  #TODO
  protect_from_forgery with: :null_session
end
class Api::ApicController
其他API控制器

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

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

您使用哪个rails环境来测试控制器的方法?我使用的是开发环境(使用Cloud9IDE)。现在正试图找出@MaxWilliams建议的post。如果您只想使用json请求测试组织创建,请尝试在测试环境中启动rails。谢谢,我使用::null_session,:If=>Proc.new{c | c.request.format=='application/json'}将其用于