我正在为 Rails 应用程序编写一个机架中间件组件,该组件需要有条件地设置 cookie。我目前正在尝试设置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。我究竟做错了什么?
如果要使用 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 标头。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)