【问题标题】:Caching JSON actions in Rails with caches_action在 Rails 中使用 caches_action 缓存 JSON 动作
【发布时间】:2014-12-24 06:11:45
【问题描述】:

我在 Rails 控制器中缓存 JSON 操作时遇到问题。发生的情况是,我从 Android 应用程序向端点发出请求,在标头中指定 mime 类型 "application/json",但响应为 "text/html"

这是我唯一使用caches_action 的操作,并且我正在使用caches_action,因此不会跳过我的过滤器(如pages_action)。

我正在使用:

caches_action :cards, expires_in: 1.day,
               cache_path: "mobile/cards/card_id_#{params[:card_id]}"

如果我将 .json 附加到请求 url,它会起作用,但我不想这样做,因为此应用程序中的所有其他 JSON 端点都不需要这样做。

为什么 Rails 强制将响应提供为 "text/html"

我可能做错了什么?

【问题讨论】:

    标签: ruby-on-rails ruby json api caching


    【解决方案1】:

    我只是通过将format: :json 添加到路由来解决问题,正如official documentation 所说:

    虽然考虑了 :format 参数。按 MIME 类型缓存最安全的方法是在路由中传递格式。

    【讨论】:

    • 嘿@rodrigoalves,你能更详细一点吗?或许可以举个例子?
    • 嗨,一个例子是resources :posts, format: :json
    猜你喜欢
    • 1970-01-01
    • 2012-08-15
    • 1970-01-01
    • 1970-01-01
    • 2015-05-07
    • 1970-01-01
    • 2015-05-08
    • 2012-05-26
    • 2011-06-03
    相关资源
    最近更新 更多