Ajax 响应 : cannot read all the headers from the response

标签 ajax response-headers

我正在使用 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

我在 chrome 开发者工具中看到: enter image description here

如何获取所有这些 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/

相关文章:

javascript - 没有浏览器是否可以进行ajax调用?

javascript - 如何使用 Ajax 添加更多过滤器和寻呼机

javascript - 通过使用回调重用我的 AJAX post 函数

jquery - 为什么 CORS AJAX 响应的响应 header 为空?

asp.net-web-api - 从 web-api 返回到 Swagger-ui 的位置响应头

javascript - Ajax 图片上传使用序列化方法

ajax - IE https CORS XHR 请求失败,并出现 Script7002 : XMLHttpRequest: Network Error 0x2eff

tomcat - 如何修改带有阀的Tomcat的响应头?

promise - 从 axios 中的响应头获取数据