XMLHttpRequest 的 getResponseHeader() 的限制?
我注意到 XMLHttpRequest.getResponseHeader()
的结果并不总是与返回的真实标头匹配(如果请求是以常规方式发出的).
I've noticed that the results of and XMLHttpRequest.getResponseHeader()
don't always match the real headers returned (if the request is made in a regular manner).
例如,假设我正在为 https://foo.example.com/api/resource/100
发出 xhr
请求.在 Chrome 的开发者控制台中,在网络"下,我可以看到正在做出的响应——我还可以看到所有响应标头(比如 10).但是(复制粘贴控制台):
For example, assume I'm making an xhr
request for https://foo.example.com/api/resource/100
. In Chrome's developer console, under 'Network', I can see the response being made -- I can also see all of the response headers (say, 10). However (copy-pasted console):
> response
XMLHttpRequest
> response.getAllResponseHeaders();
"content-type: text/html
"
对可用的标头有任何限制吗?这取决于响应类型吗?我记得有一套完整的 404 标头,但只有这个 400 的标头.
Are there any restrictions on what headers are available? Is this dependent on the response type? I remember getting a complete set of headers for 404s but just this one for 400s.
什么给了?
推荐答案
XMLHttpRequest 的标准化现状API 仅限制对 Set-Cookie 和 Set-Cookie2 标头字段的访问:
The current state of standardizing the XMLHttpRequest API does only restrict the access to the Set-Cookie and Set-Cookie2 header fields:
客户端.getAllResponseHeaders()
client.getAllResponseHeaders()
返回响应中的所有标头,字段名称为 Set-Cookie
或 Set-Cookie2
的标头除外.
Returns all headers from the response, with the exception of those whose field name is Set-Cookie
or Set-Cookie2
.
应返回任何其他标头字段.
Any other header field should be returned.
但是当你做一个跨域请求时,浏览器需要实现 XMLHttpRequest Level 2 因为原来的 XMLHttpRequest 只允许同源请求:
But as you’re doing a cross-origin request, the browser needs to implement XMLHttpRequest Level 2 as the original XMLHttpRequest does only allow same-origin requests:
XMLHttpRequest Level 2 规范增强了 XMLHttpRequest 对象的新特性,例如跨域请求 […]
The XMLHttpRequest Level 2 specification enhances the XMLHttpRequest object with new features, such as cross-origin requests […]
在那里你可以读到跨源资源共享规范过滤了那些过滤由 getResponseHeader() 公开的标头,用于非 same-origin 请求.".并且该规范禁止访问除 简单响应头字段(即Cache-Control、Content-Language、Content-Type、Expires、Last-Modified 和 Pragma):
There you can read that the "Cross-Origin Resource Sharing specification filters the headers that filters the headers that are exposed by getResponseHeader() for non same-origin requests.". And that specification forbids access to any response header field other except the simple response header fields (i.e. Cache-Control, Content-Language, Content-Type, Expires, Last-Modified, and Pragma):
用户代理必须过滤掉除简单响应头之外的所有响应头 […]
User agents must filter out all response headers other than those that are a simple response header […]
例如因此,XMLHttpRequest 的 getResponseHeader()
方法不会暴露上面未指明的任何标头.
E.g. the getResponseHeader()
method of XMLHttpRequest will therefore not expose any header not indicated above.
相关文章