Force all received requests Content-Type to JSON

99封情书 提交于 2019-12-04 00:09:45
class V1::RegistrationsController < ApplicationController
  respond_to :json
end

Makes the default reponse format json

You could define a any type response inside the respond_to block, which will not restrict your controller to respond when request uri ends with .json, it also relief you from defining a response type explicitly and will keep, independently of request content-type, responding as you wish, example:

respond_to do |format|
  format.any  {render :json => {foo: 'bar'}}
end
house9

you should be able to set the default format using routes: http://guides.rubyonrails.org/routing.html#defining-defaults

resources :registrations, ... defaults: { format: 'json' }

see also: How to set the default format for a route in Rails? format-for-a-route-in-rails?answertab=active#tab-top


Also maybe of interest:

Rails ignores the accept header when it contains “,/” or “/,” and returns HTML (or JS if it’s a xhr request).

This is by design to always return HTML when being accessed from a browser.

This doesn’t follow the mime type negotiation specification but it was the only way to circumvent old browsers with bugged accept header. They had he accept header with the first mime type as image/png or text/xml.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!