I am using Angular 2 to request JSON from my Rails API server. My server is set to respond with a header X-Total-Count: 10
. My server is successfully sending those headers:
But when I try to console.log(res.headers)
the http response, I only receive a _headersMap
with Content-Type
and Cache-Control
:
Here is my Rack::Cors config:
config.middleware.insert_before 0, "Rack::Cors" do
allow do
origins '*'
resource '*', headers: :any, methods: [:get, :post, :options, :patch, :delete], expose: ['X-Total-Count']
end
end
And the way I'm setting the headers in the controller:
def index
...
@posts = ...
response.headers['X-Total-Count'] = '10'
response.headers['Access-Control-Allow-Headers'] = 'X-Total-Count'
render json: @posts
end
How can I ensure that the X-Total-Count
is appears in the _headersMap
? Or, how can I access the X-Total-Count
value response?
Found the issue. Even though I was exposing the header through the Rack::Cors
configuration, it didn't work until I made changes to fix this deprecation. Now, the following configuration, set in config/initializers/cors.rb
, properly exposes the headers:
Rails.application.config.middleware.insert_before 0, Rack::Cors do
allow do
origins '*'
resource '*',
headers: :any,
methods: [:get, :post, :put, :patch, :delete, :options, :head],
expose: ['X-Total-Count']
end
end
According to this bug posted in alpha this is caused by your browser considering certain headers "unsafe" and rejecting their access. The fix in that thread was to add a header to your server response:
access-control-expose-headers: x-total-count
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