我正在使用 ajax (CORS
) 发出一个 post 请求,我正在设置一个 header (Content-Type:application/x-www-form-urlencoded
)我正在尝试阅读响应的 header 。这是我所做的:
function makePostRequest(url, data, headers, httpVerb, dataType, elementId) {
$.ajax({
url: url,
type: httpVerb,
data: data,
headers: headers,
dataType: dataType,
success: function(data, textStatus, jqXHR) {
$("#" + elementId).val(jqXHR.responseText);
alert(JSON.stringify(jqXHR));
},
error: function(jqXHR, textStatus, errorThrown) {
$("#" + elementId).val(jqXHR.responseText);
}
}).then(function(data, status, xhr) {
console.log(xhr.getAllResponseHeaders());
});
}
但在控制台只打印
Content-Type: application/x-www-form-urlencoded; charset=utf-8
如何获取所有这些 header ?
PS:我用的是Chrome,不是Firefox()
我问的是如何获取所有 header ,而不是为什么我只获取一个 header (如果不可能,我会接受这个答案)。
最佳答案
所以,我发出了一个 CORS
请求,在这种情况下,出于安全原因, header 被过滤掉了。
访问这些 header 的唯一方法是在响应中包含一个 header Access-Control-Expose-Headers
,它将包含一个 header 列表,您可以从 javascript 中读取这些 header 阅读 here :
7.1.1 Handling a Response to a Cross-Origin Request
User agents must filter out all response headers other than those that are a simple response header or of which the field name is an ASCII case-insensitive match for one of the values of the Access-Control-Expose-Headers headers (if any), before exposing response headers to APIs defined in CORS API specifications.
关于 Ajax 响应 : cannot read all the headers from the response,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41723138/