【问题标题】:Creating Cookies while rendering JSON在呈现 JSON 时创建 Cookie
【发布时间】:2015-05-16 02:18:11
【问题描述】:

我觉得应该是一个我一直无法解决的简单问题。我正在尝试在 Rails 4 应用程序中呈现 json 数据时设置 cookie。

def index
   request.cookies[:hi] = 'hello'
   render json: User.all
end

我一直在尝试使用 ActionDispatch::Cookies、在 cookie 变量中设置键/值以及我在 Google 搜索时看到的各种其他方法,但似乎没有任何效果。有什么建议么?这不能渲染json吗?

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 cookies


    【解决方案1】:
        def index
           cookies[:hi] = "hello" 
           render json: User.all
        end
    
    # Set a cookie that expires in 1 hour
    cookies[:login] = { :value => "XJ12", :expires => Time.now + 3600}
    # delete cookie
    cookies.delete :login
    
    
    
    
    All the option symbols for setting cookies are:
    
    value - the cookie.s value or list of values (as an array).
    path - the path for which this cookie applies. Defaults to the root of the application.
    domain - the domain for which this cookie applies.
    expires - the time at which this cookie expires, as a +Time+ object.
    secure - whether this cookie is a secure cookie or not (default to false). Secure cookies are only transmitted to HTTPS servers.
    

    这是正确的方法...

    【讨论】:

    • 我已经更正了我的代码以匹配您的代码,并重新启动了我的应用程序,但没有出现任何内容。
    • 太棒了... :) @user2684405
    • @Milind 无法设置 HttpOnly ?
    • 在 json 中设置 cookie 就像设置键值一样简单......就是这样。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-23
    • 1970-01-01
    • 2021-12-01
    • 2016-02-03
    • 2012-10-09
    • 1970-01-01
    相关资源
    最近更新 更多