有人知道如何使用JavaScript或jQuery添加或创建自定义HTTP头吗?
当前回答
使用XMLHttpRequest对象的“setRequestHeader”方法
http://help.dottoro.com/ljhcrlbv.php
其他回答
不使用jQuery也可以做到这一点。重写XMLHttpRequest的send方法,并在那里添加报头:
XMLHttpRequest.prototype.realSend = XMLHttpRequest.prototype.send;
var newSend = function(vData) {
this.setRequestHeader('x-my-custom-header', 'some value');
this.realSend(vData);
};
XMLHttpRequest.prototype.send = newSend;
使用XMLHttpRequest对象的“setRequestHeader”方法
http://help.dottoro.com/ljhcrlbv.php
你可以使用js的fetch
async function send(url,data) { let r= await fetch(url, { method: "POST", headers: { "My-header": "abc" }, body: JSON.stringify(data), }) return await r.json() } // Example usage let url='https://server.test-cors.org/server?enable=true&status=200&methods=POST&headers=my-header'; async function run() { let jsonObj = await send(url,{ some: 'testdata' }); console.log(jsonObj[0].request.httpMethod + ' was send - open chrome console > network to see it'); } run();
假设JQuery ajax,您可以添加自定义标题,如-
$.ajax({
url: url,
beforeSend: function(xhr) {
xhr.setRequestHeader("custom_header", "value");
},
success: function(data) {
}
});
或者,如果你想为以后的每个请求发送自定义报头,那么你可以使用以下方法:
$.ajaxSetup({
headers: { "CustomHeader": "myValue" }
});
这样,以后的每个ajax请求都将包含自定义头,除非被请求的选项显式地覆盖。你可以在这里找到更多关于ajaxSetup的信息
推荐文章
- React-Native:应用程序未注册错误
- LoDash:从对象属性数组中获取值数组
- src和dist文件夹的作用是什么?
- jQuery UI对话框-缺少关闭图标
- 如何使用AngularJS获取url参数
- 将RGB转换为白色的RGBA
- 如何将“camelCase”转换为“Camel Case”?
- 我们可以在另一个JS文件中调用用一个JavaScript编写的函数吗?
- 如何使用JavaScript重新加载ReCaptcha ?
- jQuery。由于转义了JSON中的单引号,parseJSON抛出“无效JSON”错误
- 在JavaScript关联数组中动态创建键
- ReactJS和公共文件夹中的图像
- 在React Native中使用Fetch授权头
- 为什么我的球(物体)没有缩小/消失?
- 如何使用jQuery检测页面的滚动位置