To find the incoming content type, docs say:
request.headers["Content-Type"] # => "text/plain"
But I found by trial-and-error, that doesn't work, but this does:
request.headers["CONTENT_TYPE"]=='application/json'
So what's the most robust+portable way to do it?
The content type of the requests for these is always x-www-form-urlencoded, since that is all that is allowed for GET and DELETE requests by the HTTP protocol. The client indicates what content type it can accept in the response by supplying an Accept header.
Since (by validity of the input spec) there are no content types for GET requests, you will always default to application/json .
Content-type is about the content of the current request or response, depending on which kind of HTTP message it is applied. So if a request has no payload, you don't have to send a content-type request header, and the same goes for your response: no body, no header necessary.
The Content-Type http request header specifies the content type of the http request payload. The Content-Type header is NOT tied to the content type of the response sent by the server. Here's an example using pure JavaScript to make an asynchronous HTTP request from the browser.
I would usually go for request.format
and request.content_type
for reading these header fields.
EDIT: found a bit more on this that might help: https://stackoverflow.com/a/1595453/624590
You don't need to parse the content_type string, Rails has already done this for you. Just check:
request.format.symbol == :json
Another way of writing it:
request.format.json?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With