Rails呈现错误的格式类型

时间:2017-07-25 15:40:11

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

我遇到rails respond_with的问题,有时候当我通过浏览器访问时,它会渲染json而不是html。有时不会出现问题,通常是在加载时间很长时。

这是规范

  1. 在控制器中,我使用respond_to :html, :json
  2. 在最后一条行动声明中,我使用了respond_with(@object)
  3. 我对浏览器(html)和mobile(json)使用相同的端点(即/ reports,not / reports和/reports.json),json请求通过将http标头与accept: application/json相关联来完成。它适用于json请求,只有html请求有时会呈现json而不是html
  4. ruby​​ v2.3.1和rails v4.2.6
  5. 仅在使用nginx服务器进行生产时才会发生,从未在开发中发生
  6. 生产服务器:unicorn v5.1.0
  7. 我使用自己的响应器获取json密钥而不是格式化错误消息,当记录无效时,在ApplicationController中我放self.responder = ApiResponder
  8. 这是ApiResponder的代码:

    class ApiResponder < ActionController::Responder
      def json_resource_errors
        I18n.locale = "json"
        resource.valid? # this refreshes locale in which error messages are translated
        { errors: resource.errors }
      end
    
      protected
    
        def api_behavior
          raise MissingRenderer.new(format) unless has_renderer?
    
          if get?
            display resource
          elsif post?
            display resource, :status => :created, :location => api_location
          elsif patch? or put?
            display resource, :status => :ok, :location => api_location
          else
            head :no_content
          end
        end
    end
    

    这是来自rails请求的日志,当它错误地呈现json而不是html:

    I, [2017-07-25T02:50:02.594851 #23977]  INFO -- : Started GET "/reports" for x.x.x.x at 2017-07-25 02:50:02 +0000
    I, [2017-07-25T02:50:02.596151 #23977]  INFO -- : Processing by ReportsController#index as HTML
    I, [2017-07-25T02:50:03.237783 #23977]  INFO -- :   Rendered regions/_region.json.jbuilder (0.4ms)
    I, [2017-07-25T02:50:03.238063 #23977]  INFO -- :   Rendered sales/_sales.json.jbuilder (1.0ms)
    ...truncated...
    I, [2017-07-25T02:50:03.284629 #23977]  INFO -- :   Rendered reports/index.json.jbuilder (61.7ms)
    I, [2017-07-25T02:50:03.285204 #23977]  INFO -- : Completed 200 OK in 689ms (Views: 56.0ms | ActiveRecord: 68.7ms)
    

    如您所见,rails将请求视为HTML,但我不知道它为什么呈现json。

    在正常呈现html时,这里是日志:

    I, [2017-07-25T02:52:05.132039 #8991]  INFO -- : Started GET "/reports" for x.x.x.x at 2017-07-25 02:52:05 +0000
    I, [2017-07-25T02:52:05.187351 #8991]  INFO -- : Processing by ReportsController#index as HTML
    I, [2017-07-25T02:52:06.115379 #8991]  INFO -- :   Rendered shared/_filter_date.html.erb (1.0ms)
    I, [2017-07-25T02:52:06.161682 #8991]  INFO -- :   Rendered reports/_reports.html.erb (45.6ms)
    I, [2017-07-25T02:52:06.163072 #8991]  INFO -- :   Rendered reports/index.html.erb within layouts/application (51.2ms)
    I, [2017-07-25T02:52:06.181696 #8991]  INFO -- : Completed 200 OK in 994ms (Views: 66.3ms | ActiveRecord: 84.9ms)
    

    上述两个请求都是从浏览器访问的,但前者呈现json(应该是html)。

    我想知道这是否与服务器或生产配置和生产相关,因为它永远不会在开发中发生。

0 个答案:

没有答案