我遇到rails respond_with
的问题,有时候当我通过浏览器访问时,它会渲染json而不是html。有时不会出现问题,通常是在加载时间很长时。
这是规范
respond_to :html, :json
respond_with(@object)
accept: application/json
相关联来完成。它适用于json请求,只有html请求有时会呈现json而不是html self.responder = ApiResponder
这是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)。
我想知道这是否与服务器或生产配置和生产相关,因为它永远不会在开发中发生。