Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Angular 2 response headers

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:

Server Response

But when I try to console.log(res.headers) the http response, I only receive a _headersMap with Content-Type and Cache-Control:

enter image description here

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?

like image 270
Louis Cruz Avatar asked Jan 06 '23 07:01

Louis Cruz


2 Answers

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
like image 101
Louis Cruz Avatar answered Jan 14 '23 13:01

Louis Cruz


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
like image 38
casey Avatar answered Jan 14 '23 14:01

casey