I have some frontend javascript that makes an asynchronous http request to my backend rails server. On the frontend I am not using XHR (I use axios
, although that's not entirely relevant to the question).
In the request, I set the following to tell the server I'm sending JSON and to make sure I get JSON back:
const config = {
headers: {
"Content-Type": "application/json",
"Accept": "application/json"
}
};
In my backend Rails controller if inspect the request I can verify the Accept
header:
> request.headers
"HTTP_ACCEPT"=>"application/json, text/plain, */*"
However ActionPack/Rails still does not respect that and defaults to the format
being :html
> request.format
=> #<Mime::Type:0x00007fe223919f80 @hash=-1773238723920954657, @string="text/html", @symbol=:html, @synonyms=["application/xhtml+xml"]>
Why is that?
I know I can append .json
to my request URL to "force" it to specify that format, but is that the only option? I can append it easily but it seems like an implementation specific to Rails and not really the "right" approach.
Additionally, the source code for the request.format
method explicitly sets :json
as the format on XHR requests - does rails only respect XHR requests at the moment?
Thanks!