简体   繁体   中英

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:

服务器响应

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

It's because of CORS. You're only be able to see the header in the map only if it's enabled by CORS.

Your server needs to return the following in headers:

Access-Control-Allow-Headers: X-Total-Count

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM