Nic*_*ick 4 ruby api ruby-on-rails authenticity-token ruby-on-rails-4
我正在尝试为我的 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
Run Code Online (Sandbox Code Playgroud)
在 Postman 中尝试该方法会返回错误:“无法验证 CSRF 令牌的真实性”。基于这篇文章,我将下面的代码添加到基本控制器中。不幸的是,这没有什么区别。有人了解错误的原因吗?
protect_from_forgery
skip_before_action :verify_authenticity_token, if: :json_request?
private
def json_request?
request.format.json?
end
Run Code Online (Sandbox Code Playgroud)
根据评论,application_controller.rb您需要添加这一行
protect_from_forgery with: :null_session。
如果您只为所有继承自ApplicationController. IE
class Api::ApiController < ApplicationController
#TODO
protect_from_forgery with: :null_session
end
Run Code Online (Sandbox Code Playgroud)
其他API的控制器
class Api::V1::AddressesController < Api::ApiController
#TODO
end
Run Code Online (Sandbox Code Playgroud)
该控制器类可以帮助您仅对 API 的根而不是整个应用程序进行更改。您还可以使用此控制器在不同版本的 API 之间进行 DRY 操作。
| 归档时间: |
|
| 查看次数: |
2205 次 |
| 最近记录: |