【问题标题】:Why doesn't session[:] work in grape - rails?为什么 session[:] 不能在葡萄-rails 中工作?
【发布时间】:2016-02-11 16:01:07
【问题描述】:

我正在使用带有 Grape 作为 API 的 Rails。我只是好奇为什么葡萄中没有session[:something] 方法?我可以创建 cookie,但也不能创建签名 cookie。它给我一个错误。

【问题讨论】:

    标签: ruby-on-rails session grape


    【解决方案1】:

    Grape 是一个用于构建 API 的轻量级框架,当您向 Grape API 端点发送请求时,响应不会通过所有 Rails 中间件,而是通过一组精简的 Rack 中间件。因此,Grape 专为构建 API 而设计,您可以在其中插入所需的中间件,具体取决于您的要求。主要目标是使 API 尽可能轻量级,并提高速度和性能。

    如果你想在 Rails 上挂载的 Grape 中启用会话,你需要使用 ActionDispatch::Session::CookieStore 中间件。

    class API < Grape::API
      use ActionDispatch::Session::CookieStore
    
      helpers do
       def session
         env['rack.session']
       end
      end
    
      post :session do
       session[:foo] = "grape"
      end
    
      get :session do
        { session: session[:foo] }
      end
    end
    

    您可以将grape_session gem 用于上述目的。

    如果您想在没有 Rails 中间件的情况下在 Rack 应用程序中使用默认的会话方式,请使用 Rack 中可用的默认 Rack::Session::Cookie 中间件。

    【讨论】:

    • 如果你想与 Rails 共享会话,你也需要像这样指定密钥:use ActionDispatch::Session::CookieStore, key: '_XXX_session'
    • 如果您使用 xhr 向您的 api 端点发送请求,请确保 cookie 存在于请求标头中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-28
    • 1970-01-01
    • 1970-01-01
    • 2014-12-06
    • 1970-01-01
    相关资源
    最近更新 更多