gpt4 book ai didi

ruby-on-rails - API/JSON : Can't verify CSRF token authenticity

转载 作者:数据小太阳 更新时间:2023-10-29 07:31:45 36 4
gpt4 key购买 nike

我正在尝试为我的 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 token 真实性”。基于this post我将下面的代码添加到基本 Controller 。不幸的是,这没有任何区别。有谁知道错误的原因吗?

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 Controller 再创建一个根 Controller 会更好。即

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

其他API的 Controller

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

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

关于ruby-on-rails - API/JSON : Can't verify CSRF token authenticity,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34851538/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com