为什么Etag
标题在以下最小示例中未由jqXHR.getAllResponseHeaders()
返回?
使用:node etag-server.js
运行(然后访问http://localhost:8080/
)
ETAG-server.js
var fs = require('fs'),
http = require('http');
var webServer = http.createServer(function (request, response) {
response.writeHead(200, {"Content-Type": "text/html"});
response.end(fs.readFileSync('frontend.html'));
});
var apiServer = http.createServer(function (request, response) {
response.writeHead(200, {
'Access-Control-Allow-Origin': 'http://localhost:8080',
'Cache-Control': 'no-cache',
'Content-Type': 'application/json; charset=utf-8',
'Etag': 123,
'Expires': -1,
'Pragma': 'no-cache'
});
response.end(JSON.stringify({ data: [1, 2, 3] }));
});
webServer.listen(8080);
apiServer.listen(8081);
frontend.html
<!DOCTYPE html>
<html>
<head>
<title>Etag header not returned from jQuery.ajax() cross-origin XHR</title>
<script src="//code.jquery.com/jquery-1.10.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$.ajax('//localhost:8081/')
.done(function (data, textStatus, jqXHR) {
$('pre').text(jqXHR.getAllResponseHeaders());
})
.fail(function (jqXHR, textStatus, errorThrown) { $('pre').text(textStatus); });
});
</script>
</head>
<body>
<pre></pre>
</body>
</html>
页面输出
Cache-Control: no-cache
Content-Type: application/json; charset=utf-8
Expires: -1
Pragma: no-cache
Etag
去了哪里?他们被发送到浏览器:
HTTP/1.1 200 OK
Access-Control-Allow-Origin: http://localhost:8080
Cache-Control: no-cache
Content-Type: application/json; charset=utf-8
Etag: 123
Expires: -1
Pragma: no-cache
Date: Sat, 25 Jan 2014 02:20:47 GMT
Connection: keep-alive
Transfer-Encoding: chunked
(由Firebug报道)
答案 0 :(得分:18)
除非服务器在其响应中包含Access-Control-Expose-Headers
标头,其值为“ETag”,否则客户端代码将无法访问跨源响应中存在的ETag标头。任何“非简单”响应标头都是如此。
来自CORS spec:
7.1.1处理对跨源请求的响应 用户代理必须过滤掉除了那些简单响应头之外的所有响应头,或者其字段名是对Access-Control-Expose-Headers头(如果有)的值之一的ASCII不区分大小写的匹配,在将响应头暴露给CORS API规范中定义的API之前。
简单的响应标头仅限于:
客户端需要在响应中访问的所有其他标头必须通过我上面提到的响应标头“公开”。