1

我正在尝试使用 Rack Middleware 设置 cookie 并在相同的请求 - 响应周期中发送有效 cookie 的响应。

这里是上下文:我在一个有两种模式的网站上工作:美国模式和英国模式(不同的标志、导航栏、样式等)。当英国访问者第一次访问该页面时,我想在他的浏览器上设置一个“英国模式”cookie,但同时也呈现该页面的英国版本。到目前为止,这是我的代码:

 # middleware/geo_filter_middleware.rb

 def initialize(app)
   @app = app
 end

 def call(env)
   status, headers, body = @app.call(env)
   response = Rack::Response.new(body, status, headers)
   if from_uk?(env)
      response.set_cookie('country', 'UK')
   end
   response.to_a
 end

当英国访问者第一次访问该页面时,它会在他们的 cookie 中设置“英国模式”,但仍会呈现页面的默认美国版本。只有在第二次请求之后 cookie 才会生效并且英国访问者会看到英国模式。

有谁知道在一个请求-响应周期中同时设置 cookie 并返回有效 cookie 的响应?

4

1 回答 1

3

你需要在你的 application.rb 中设置你的中间件

config.middleware.insert_before "ActionDispatch::Cookies", "GeoFilterMiddleware"

并在您的中间件中执行以下操作:

  def call(env)
    status, headers, body = @app.call(env)
    if from_uk?(env)
      Rack::Utils.set_cookie_header!(headers, 'country', { :value => 'UK', :path => '/'})
    end
    [status, headers, body]
  end
于 2013-07-09T09:44:39.063 回答