JS/jQuery 获取 HTTPRequest 请求标头?

场景:在jquery封装的ajax请求中,默认是异步请求。

需要定一个秘钥进行解密,所以只能存放在请求头中。然后需要值的时候去请求头中读取。

注意:dataType 设置,根据请求参数的格式设置,如果是加密字符串,就设置为text,如果是json,就设置为json,否则,接口请求状态码是200,但是会进入到error函数中。

javascript 复制代码
$.ajax({
    url: 'url',
    data:{'req':somedata},
    type:"post",
    cache:'false',
    dataType:'json',//注:
    headers:{'key':'bar'},  //设置请求头
    success: function() {
        alert(this.headers.key);//获取请求头
    },
    error:function(){
    }
});

目前到上面我的问题就解决了。

参考文章:https://www.it1352.com/2772303.html

但是我认为只有已经在 headers 中定义的标题是可用的(不确定如果标题被改变会发生什么(例如在 beforeSend 中).

您可以在以下位置阅读更多关于 jQuery ajax 的信息:http://api.jquery.com/jQuery.ajax/

如果您只想捕获对 XMLHttpRequest 上的 setRequestHeader 的所有调用的标头,那么您可以包装该方法.这有点麻烦,当然您需要确保在任何请求发生之前运行包装下面的代码的函数.

javascript 复制代码
// Reasign the existing setRequestHeader function to 
// something else on the XMLHtttpRequest class
XMLHttpRequest.prototype.wrappedSetRequestHeader = 
  XMLHttpRequest.prototype.setRequestHeader; 

// Override the existing setRequestHeader function so that it stores the headers
XMLHttpRequest.prototype.setRequestHeader = function(header, value) {
    // Call the wrappedSetRequestHeader function first 
    // so we get exceptions if we are in an erronous state etc.
    this.wrappedSetRequestHeader(header, value);

    // Create a headers map if it does not exist
    if(!this.headers) {
        this.headers = {};
    }

    // Create a list for the header that if it does not exist
    if(!this.headers[header]) {
        this.headers[header] = [];
    }

    // Add the value to the header
    this.headers[header].push(value);
}

现在,一旦在 XMLHttpRequest 实例上设置了标头,我们就可以通过检查 xhr.headers 例如

javascript 复制代码
var xhr = new XMLHttpRequest();
xhr.open('get', 'demo.cgi');
xhr.setRequestHeader('foo','bar');
alert(xhr.headers['foo'][0]); // gives an alert with 'bar'
相关推荐
犇驫聊AI8 小时前
Chrome DevTools MCP + Claude Code 自定义skills生成接口代码生成器
前端·javascript
kyriewen8 小时前
别再这样写 async/await 了:我在 Code Review 中见过最多的 8 个错误
前端·javascript·面试
用户2986985301413 小时前
在 React 中使用 JavaScript 将 Excel 转换为 SVG
前端·javascript·react.js
labixiong13 小时前
手写Promise--微任务、静态方法、async/await 全搞懂(三)
前端·javascript
铁皮饭盒15 小时前
3行代码搞定页面截图,Bun.WebView真的简单
javascript
kyriewen1 天前
我手写了一个 EventEmitter,面试官追问了 6 个问题——第 4 个我没答上来
前端·javascript·面试
山河木马1 天前
矩阵专题2-怎么创建视图矩阵(uViewMatrix)
javascript·webgl·计算机图形学
tangdou3690986551 天前
AI真好玩系列-2分钟快速了解DeepAgents | Quick Guide to DeepAgents in 2 Minutes
前端·javascript·后端
张元清1 天前
React useIntersectionObserver Hook:懒加载与可见性检测(2026)
javascript·react.js
彭于晏爱编程1 天前
纯 JS + Node,一个下午手搓了能读懂公司代码的 AI 助手,老板以为我转行了
前端·javascript