如何使用(ruby)机架中间件组件设置 cookie?
我正在为 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。我做错了什么?
I'm writing a rack middleware component for a rails app that will need to conditionally set cookies. I am currently trying to figure out to set cookies. From googling around it seems like this should work:
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
which doesn't give errors, but doesn't set a cookie either. What am I doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果要使用 Response 类,则需要根据调用堆栈中更下方的中间件层的结果来实例化它。
另外,您不需要像这样的中间件的实例变量,并且可能不想以这种方式使用它们(@status 等将在请求提供后保留在中间件实例中)
如果您知道自己在做什么如果您不想实例化新对象,可以直接修改 cookie 标头。
If you want to use the Response class, you need to instantiate it from the results of calling the middleware layer further down the stack.
Also, you don't need instance variables for a middleware like this and probably don't want to use them that way(@status,etc would stay around in the middleware instance after the request is served)
If you know what you are doing you could directly modify the cookie header, if you don't want to instantiate a new object.
您还可以使用 Rack::Utils 库来设置和删除标头,而无需创建 Rack::Response 对象。
You can also use the
Rack::Utils
library to set and delete headers without creating a Rack::Response object.