当前位置: 首页 > news >正文

JS/jQuery 获取 HTTPRequest 请求标头?

场景:在jquery封装的ajax请求中,默认是异步请求。
需要定一个秘钥进行解密,所以只能存放在请求头中。然后需要值的时候去请求头中读取。

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

$.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 的所有调用的标头,那么您可以包装该方法.这有点麻烦,当然您需要确保在任何请求发生之前运行包装下面的代码的函数.

// 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 existif(!this.headers) {this.headers = {};}// Create a list for the header that if it does not existif(!this.headers[header]) {this.headers[header] = [];}// Add the value to the headerthis.headers[header].push(value);
}

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

var xhr = new XMLHttpRequest();
xhr.open('get', 'demo.cgi');
xhr.setRequestHeader('foo','bar');
alert(xhr.headers['foo'][0]); // gives an alert with 'bar'
http://www.lryc.cn/news/255100.html

相关文章:

  • Leetcode—2034.股票价格波动【中等】
  • 【Linux】diff命令使用
  • 讯飞星火认知大模型与软件测试结合,提升软件质量与效率
  • 【Flink on k8s】- 4 - 在 Kubernetes 上运行容器
  • 软件重装或系统重装后避免重复踩坑
  • 【Jmeter】JSON Extractor变量包含转义字符,使用Beanshell脚本来消除
  • GO设计模式——5、建造者模式(创建型)
  • 《LeetCode力扣练习》代码随想录——字符串(反转字符串II---Java)
  • WMMSE方法的使用笔记
  • MySQL核心知识点整理大全1-笔记
  • 理解输出电压纹波和噪声:来源与抑制
  • uni-app 微信小程序之好看的ui登录页面(二)
  • Textual Inversion
  • 笙默考试管理系统-MyExamTest----codemirror(47)
  • JVM中 Minor GC 和 Full GC 的区别
  • 二十一章(网络通信)
  • [linux运维] 利用zabbix监控linux高危命令并发送告警(基于Zabbix 6)
  • 手机升级到iOS15.8后无法在xcode(14.2)上真机调试
  • 安装TensorFlow2.12.0
  • elasticsearch 索引数据多了怎么办,如何调优,部署?
  • 人工智能企业引入S-SDLC,推动安全能力大跃升,保障AI技术体系深化落地
  • Docker的数据卷
  • 第二十一章总结博客
  • 学习php中使用composer下载安装firebase/php-jwt 以及调用方法
  • 『TypeScript』深入理解变量声明、函数定义、类与接口及泛型
  • 如何优雅使用 vue-html2pdf 插件生成pdf报表
  • C语言第十六集(前)
  • Makefile语法
  • 用户案例|Milvus 助力 Credal.AI 实现 GenAI 安全与可控
  • MySQL三 | 多表查询