ajax响应:无法读取响应中的所有标头 [英] ajax response: cannot read all the headers from the response
问题描述
我正在使用ajax( CORS
)发出发布请求,并设置了标头( Content-Type:application/x-www-form-urlencoded
)并且我正在尝试读取响应的标题.这是我所做的:
I'm making a post request with ajax (CORS
) and I am setting a header (Content-Type:application/x-www-form-urlencoded
) and I'm trying to read the response's headers. Here is what I've done:
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
在chrome开发人员工具中,我看到了:
And in chrome developer tools I'm seeing:
如何获取所有这些标头?
How to get all these headers?
PS:我使用的是Chrome,而不是Firefox()
PS: I am using Chrome, not Firefox ()
我问如何获取所有标头,而不是为什么我只得到一个标头(如果不可能的话,我会接受这个答案).
I asked how to get all headers, not why I'm getting only one header(if it's not possible, I will accept this answer).
推荐答案
因此,我正在发出 CORS
请求,在这种情况下,出于安全原因将标头过滤掉了.
So, I was making a CORS
request and in this case the headers are filtered out for security reasons.
访问这些标头的唯一方法是在响应中包含标头 Access-Control-Expose-Headers
,该标头包含可以从javascript中读取的标头列表,您可以在此处阅读:
The only way to acces those headers is to include in the response a header Access-Control-Expose-Headers
that will contain a list of headers that can be read from the javascript, as you can read here:
7.1.1处理对跨域请求的响应
7.1.1 Handling a Response to a Cross-Origin Request
用户代理必须过滤掉除响应头以外的所有响应头是简单的响应标头,或者其字段名是ASCII大小写不敏感的匹配值之一 Access-Control-Expose-Headers 标头(如果有的话),在曝光之前对CORS API规范中定义的API的响应标头.
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响应:无法读取响应中的所有标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!