有人知道如何使用JavaScript或jQuery添加或创建自定义HTTP头吗?
当前回答
根据你的需要,有几种解决方案。
如果你想添加一个自定义头(或一组头)到一个单独的请求,那么只需要添加headers属性:
// Request with custom header
$.ajax({
url: 'foo/bar',
headers: { 'x-my-custom-header': 'some value' }
});
如果你想给每个请求添加一个默认头(或一组头),那么使用$.ajaxSetup():
$.ajaxSetup({
headers: { 'x-my-custom-header': 'some value' }
});
// Sends your custom header
$.ajax({ url: 'foo/bar' });
// Overwrites the default header with a new header
$.ajax({ url: 'foo/bar', headers: { 'x-some-other-header': 'some value' } });
如果你想给每个请求添加一个头(或一组头),那么使用$.ajaxSetup()的beforeSend钩子:
$.ajaxSetup({
beforeSend: function(xhr) {
xhr.setRequestHeader('x-my-custom-header', 'some value');
}
});
// Sends your custom header
$.ajax({ url: 'foo/bar' });
// Sends both custom headers
$.ajax({ url: 'foo/bar', headers: { 'x-some-other-header': 'some value' } });
编辑(更多信息):需要注意的一件事是,使用ajaxSetup,你只能定义一组默认头,你只能定义一个beforeSend。如果多次调用ajaxSetup,则只会发送最后一组报头,并且只会执行最后一个发送前回调。
其他回答
或者,如果你想为以后的每个请求发送自定义报头,那么你可以使用以下方法:
$.ajaxSetup({
headers: { "CustomHeader": "myValue" }
});
这样,以后的每个ajax请求都将包含自定义头,除非被请求的选项显式地覆盖。你可以在这里找到更多关于ajaxSetup的信息
不使用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();
假设你的意思是“当使用ajax”和“一个HTTP请求头”,那么在你传递给ajax()的对象中使用headers属性
头(1.5) 默认值:{} 随请求一起发送的附加头键/值对的映射。该设置是在调用beforeSend函数之前设置的;因此,在报头设置中的任何值都可以在beforeSend函数中被覆盖。
——http://api.jquery.com/jQuery.ajax/
推荐文章
- 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检测页面的滚动位置