[英]How to get Angular 2 response headers
I am using Angular 2 to request JSON from my Rails API server. 我正在使用Angular 2从我的Rails API服务器请求JSON。 My server is set to respond with a header
X-Total-Count: 10
. 我的服务器设置为响应标头
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
: 但是当我尝试使用
console.log(res.headers)
http响应时,我只收到带有Content-Type
和Cache-Control
的_headersMap
:
Here is my Rack::Cors config: 这是我的Rack :: Cors配置:
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
? 如何确保
X-Total-Count
出现在_headersMap
? Or, how can I access the X-Total-Count
value response? 或者,如何访问
X-Total-Count
值响应?
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 . 即使我通过
Rack::Cors
配置公开了标题,但在我做出修改以解决此弃用问题之前,它仍无效。 Now, the following configuration, set in config/initializers/cors.rb
, properly exposes the headers: 现在,在
config/initializers/cors.rb
设置的以下配置正确公开了标头:
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. 根据alpha中发布的这个错误,这是由于您的浏览器认为某些标题“不安全”并拒绝其访问权限。 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. 这是因为CORS。 You're only be able to see the header in the map only if it's enabled by CORS.
只有在CORS启用时,您才能在地图中看到标题。
Your server needs to return the following in headers: 您的服务器需要在标头中返回以下内容:
Access-Control-Allow-Headers: X-Total-Count
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.