gpt4 book ai didi

ruby-on-rails - 在仅 API 的 Rails 应用程序上使用 GraphQL 时,"The action ' 执行 ' could not be found for GraphqlController"?

转载 作者:行者123 更新时间:2023-12-04 05:57:59 24 4
gpt4 key购买 nike

我已经在 rmosolgo/graphql-ruby 上为此发布了一个错误但以防万一我做错了什么,我希望看看其他人是否有解决我的问题的方法。

创建仅 API 的 Rails 应用程序时,Rails 似乎相信 execute我的 GraphqlController 中的方法不见了。

这是我的 graphql_controller.rb 文件:

class GraphqlController < ApplicationController
# If accessing from outside this domain, nullify the session
# This allows for outside API access while preventing CSRF attacks,
# but you'll have to authenticate your user separately
protect_from_forgery with: :null_session

def execute
variables = ensure_hash(params[:variables])
query = params[:query]
operation_name = params[:operationName]
context = {
# Query context goes here, for example:
# current_user: current_user,
}
result = RailsApiGraphqlExecuteTestSchema.execute(query, variables: variables, context: context, operation_name: operation_name)
render json: result
rescue => e
raise e unless Rails.env.development?
handle_error_in_development e
end
# ... continues on
end

这是我的 routes.rb 文件:
Rails.application.routes.draw do
post "/graphql", to: "graphql#execute"
# For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
end

当我运行时 rake routes这就是我得到的:
prompt> rake routes                                   
Prefix Verb URI Pattern Controller#Action
graphql POST /graphql(.:format) graphql#execute
... continues on

您应该能够使用以下命令行步骤重现此问题:
rails new execute-test --api
cd execute-test
vim Gemfile # or open an editor and add "gem 'graphql'"
bundle
rake db:create
rails g graphql:install
rake routes # to test that the route exists
rails s

当您使用 GraphiQL 之类的应用程序并转到 http://localhost:3000/graphql 时你会得到以下错误:
Started POST "/graphql" for 127.0.0.1 at 2019-10-15 16:23:29 -0700
(0.3ms) SELECT sqlite_version(*)

AbstractController::ActionNotFound (The action 'execute' could not be found for GraphqlController):
... strack trace continues ...

也许我做错了什么?任何帮助将非常感激。

最佳答案

看起来像 execute 中的这一行方法:

protect_from_forgery with: :null_session

是什么导致了问题。我得再研究一下。 +1,如果有人能弄清楚为什么会发生这种情况,我什至会将答案标记为正确。

编辑:发生这种情况的原因是因为此方法假定您继承自 ActionController::Base而不是 ActionController::API (没有这种方法)。 API 类应该更轻,因此不支持开箱即用的 cookie/ session 。

关于ruby-on-rails - 在仅 API 的 Rails 应用程序上使用 GraphQL 时,"The action ' 执行 ' could not be found for GraphqlController"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58403931/

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