有人知道如何使用JavaScript或jQuery添加或创建自定义HTTP头吗?
当前回答
假设你的意思是“当使用ajax”和“一个HTTP请求头”,那么在你传递给ajax()的对象中使用headers属性
头(1.5) 默认值:{} 随请求一起发送的附加头键/值对的映射。该设置是在调用beforeSend函数之前设置的;因此,在报头设置中的任何值都可以在beforeSend函数中被覆盖。
——http://api.jquery.com/jQuery.ajax/
其他回答
你可以使用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也可以做到这一点。重写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
假设你的意思是“当使用ajax”和“一个HTTP请求头”,那么在你传递给ajax()的对象中使用headers属性
头(1.5) 默认值:{} 随请求一起发送的附加头键/值对的映射。该设置是在调用beforeSend函数之前设置的;因此,在报头设置中的任何值都可以在beforeSend函数中被覆盖。
——http://api.jquery.com/jQuery.ajax/
您应该避免使用文档中描述的$. ajaxsetup()。请使用以下语句:
$(document).ajaxSend(function(event, jqXHR, ajaxOptions) {
jqXHR.setRequestHeader('my-custom-header', 'my-value');
});