【问题标题】:How do I set a cookie with a (ruby) rack middleware component?如何使用(ruby)机架中间件组件设置 cookie?
【发布时间】:2011-03-18 17:28:51
【问题描述】:

我正在为需要有条件地设置 cookie 的 rails 应用程序编写机架中间件组件。我目前正试图弄清楚设置cookies。从谷歌搜索看来,这应该可行:

class RackApp
  def initialize(app)
    @app = app
  end

  def call(env)
    @status, @headers, @response = @app.call(env)
    @response.set_cookie("foo", {:value => "bar", :path => "/", :expires => Time.now+24*60*60})
    [@status, @headers, @response]
  end
end

它不会给出错误,但也不会设置 cookie。我做错了什么?

【问题讨论】:

    标签: ruby cookies rack middleware setcookie


    【解决方案1】:

    如果你想使用 Response 类,你需要从调用中间件层的结果中实例化它。 此外,您不需要像这样的中间件的实例变量,并且可能不想以这种方式使用它们(@status 等会在处理请求后留在中间件实例中)

    class RackApp
      def initialize(app)
        @app = app
      end
    
      def call(env)
        status, headers, body = @app.call(env)
        # confusingly, response takes its args in a different order
        # than rack requires them to be passed on
        # I know it's because most likely you'll modify the body, 
        # and the defaults are fine for the others. But, it still bothers me.
    
        response = Rack::Response.new body, status, headers
    
        response.set_cookie("foo", {:value => "bar", :path => "/", :expires => Time.now+24*60*60})
        response.finish # finish writes out the response in the expected format.
      end
    end
    

    如果您知道自己在做什么,如果您不想实例化新对象,则可以直接修改 cookie 标头。

    【讨论】:

    • 太棒了。这对我来说非常有效。迄今为止我见过的最清晰的例子。
    • 谢谢!五年后,这个 sn-p 正是我想要的。
    • @BaroqueBobcat 如果您包含如何直接修改 cookie,那将非常有用。感谢您的精彩回答!
    • 如果我们想覆盖现有的 cookie 字符串以附加 SameSite=None; 怎么办?
    【解决方案2】:

    您还可以使用Rack::Utils 库来设置和删除标头,而无需创建 Rack::Response 对象。

    class RackApp
      def initialize(app)
        @app = app
      end
    
      def call(env)
        status, headers, body = @app.call(env)
    
        Rack::Utils.set_cookie_header!(headers, "foo", {:value => "bar", :path => "/"})
    
        [status, headers, body]
      end
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-11-04
      • 1970-01-01
      • 1970-01-01
      • 2017-06-22
      • 1970-01-01
      • 1970-01-01
      • 2017-01-11
      相关资源
      最近更新 更多