問題描述
我注意到 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.
這篇關于XMLHttpRequest 的 getResponseHeader() 的限制?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!