有人知道如何使用JavaScript或jQuery添加或创建自定义HTTP头吗?
当前回答
假设JQuery ajax,您可以添加自定义标题,如-
$.ajax({
url: url,
beforeSend: function(xhr) {
xhr.setRequestHeader("custom_header", "value");
},
success: function(data) {
}
});
其他回答
使用XMLHttpRequest对象的“setRequestHeader”方法
http://help.dottoro.com/ljhcrlbv.php
假设JQuery ajax,您可以添加自定义标题,如-
$.ajax({
url: url,
beforeSend: function(xhr) {
xhr.setRequestHeader("custom_header", "value");
},
success: function(data) {
}
});
下面是一个使用XHR2的例子:
function xhrToSend(){
// Attempt to creat the XHR2 object
var xhr;
try{
xhr = new XMLHttpRequest();
}catch (e){
try{
xhr = new XDomainRequest();
} catch (e){
try{
xhr = new ActiveXObject('Msxml2.XMLHTTP');
}catch (e){
try{
xhr = new ActiveXObject('Microsoft.XMLHTTP');
}catch (e){
statusField('\nYour browser is not' +
' compatible with XHR2');
}
}
}
}
xhr.open('POST', 'startStopResume.aspx', true);
xhr.setRequestHeader("chunk", numberOfBLObsSent + 1);
xhr.onreadystatechange = function (e) {
if (xhr.readyState == 4 && xhr.status == 200) {
receivedChunks++;
}
};
xhr.send(chunk);
numberOfBLObsSent++;
};
希望这能有所帮助。
如果创建对象,可以在发送请求之前使用setRequestHeader函数分配名称和值。
您应该避免使用文档中描述的$. ajaxsetup()。请使用以下语句:
$(document).ajaxSend(function(event, jqXHR, ajaxOptions) {
jqXHR.setRequestHeader('my-custom-header', 'my-value');
});
你可以使用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();
推荐文章
- 将lodash导入到angular + typescript应用程序中
- 什么时候使用setAttribute vs .attribute=在JavaScript?
- 每60秒调用一个函数
- 我如何上传一个文件与JS获取API?
- 在JavaScript中是否有一个“not in”操作符来检查对象属性?
- 如何触发点击一个链接使用jQuery
- 我如何能得到滚动条的位置与JavaScript?
- JavaScript中的yield关键字是什么?
- 如何显示一个对象的所有方法?
- .js和.mjs文件有什么区别?
- Axios处理错误
- ESLint解析错误:意外的令牌
- 同时映射和过滤一个数组
- TypeScript:创建一个空的类型容器数组
- 在JavaScript中将大字符串分割为n大小的块