【发布时间】:2016-04-23 10:27:32
【问题描述】:
我正在尝试为我的 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 令牌真实性”。基于this post,我将以下代码添加到基本控制器中。不幸的是,这没有任何区别。有人了解错误原因吗?
protect_from_forgery
skip_before_action :verify_authenticity_token, if: :json_request?
private
def json_request?
request.format.json?
end
【问题讨论】:
-
你使用哪个 Rails 环境来测试你的控制器的方法?
-
我正在使用开发环境(使用 Cloud9 IDE)。现在正试图弄清楚@MaxWilliams 建议的帖子。
-
如果您只想使用 json 请求测试组织创建,请尝试在测试环境中启动 rails。
-
谢谢,我可以使用
protect_from_forgery with: :null_session, :if => Proc.new { |c| c.request.format == 'application/json' }
标签: ruby-on-rails ruby api ruby-on-rails-4 authenticity-token