有人知道如何使用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();