I have an application developed in Rails and I am trying to see the attributes in the HTTP header.
Is there any way to read these attributes? Where are they stored?
Someone mentioned request.headers
. Is this correct? I am not able to see any attributes inside this array.
To view the request or response HTTP headers in Google Chrome, take the following steps : In Chrome, visit a URL, right click , select Inspect to open the developer tools. Select Network tab. Reload the page, select any HTTP request on the left panel, and the HTTP headers will be displayed on the right panel.
Headers are included in a hash as the second item in the response array that our Rails app returns to our web server. Headers are simply additional information about the response. This information might provide directions for the browser, such as whether and for how long to cache the response.
An HTTP header is a field of an HTTP request or response that passes additional context and metadata about the request or response. For example, a request message can use headers to indicate it's preferred media formats, while a response can use header to indicate the media format of the returned body.
request.headers
does not return a hash, but an instance of ActionDispatch::Http::Headers
, which is a wrapper around rack env.
ActionDispatch::Http::Headers
implements many methods like []
and []=
which make it behave like a hash, but it doesn't override the default inspect
, hence you can't see the key-value pairs by just p
or pp
it.
You can, however, see the request headers in the rack env:
pp request.headers.env.select{|k, _| k =~ /^HTTP_/}
Remember that the request headers in rack env are the upcase
d, underscore
d and HTTP_
prefixed version of the original http request headers.
Actually there are a finite set of request headers that are not prefixed HTTP_
. These (capitalized and underscored) header names are stored in ActionDispatch::Http::Headers::CGI_VARIABLES
. I list them below:
AUTH_TYPE
CONTENT_LENGTH
CONTENT_TYPE
GATEWAY_INTERFACE
HTTPS
PATH_INFO
PATH_TRANSLATED
QUERY_STRING
REMOTE_ADDR
REMOTE_HOST
REMOTE_IDENT
REMOTE_USER
REQUEST_METHOD
SCRIPT_NAME
SERVER_NAME
SERVER_PORT
SERVER_PROTOCOL
SERVER_SOFTWARE
So the full version of listing request headers would be
pp request.headers.env.select{|k, _| k.in?(ActionDispatch::Http::Headers::CGI_VARIABLES) || k =~ /^HTTP_/}
This code solved my question request.env["HTTP_MY_HEADER"]
. The trick was that I had to prefix my header's name with HTTP
I've noticed in Rails 5 they now expect headers to be spelled like this in the request:
Access-Token
Before they are transformed into:
HTTP_ACCESS_TOKEN
In Rails. Doing ACCESS_TOKEN
will no longer work.
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