有人知道如何使用JavaScript或jQuery添加或创建自定义HTTP头吗?


假设你的意思是“当使用ajax”和“一个HTTP请求头”,那么在你传递给ajax()的对象中使用headers属性

头(1.5) 默认值:{} 随请求一起发送的附加头键/值对的映射。该设置是在调用beforeSend函数之前设置的;因此,在报头设置中的任何值都可以在beforeSend函数中被覆盖。

——http://api.jquery.com/jQuery.ajax/

下面是一个使用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函数分配名称和值。

假设JQuery ajax,您可以添加自定义标题,如-

$.ajax({
  url: url,
  beforeSend: function(xhr) {
    xhr.setRequestHeader("custom_header", "value");
  },
  success: function(data) {
  }
});

使用XMLHttpRequest对象的“setRequestHeader”方法

http://help.dottoro.com/ljhcrlbv.php

或者,如果你想为以后的每个请求发送自定义报头,那么你可以使用以下方法:

$.ajaxSetup({
    headers: { "CustomHeader": "myValue" }
});

这样,以后的每个ajax请求都将包含自定义头,除非被请求的选项显式地覆盖。你可以在这里找到更多关于ajaxSetup的信息

根据你的需要,有几种解决方案。

如果你想添加一个自定义头(或一组头)到一个单独的请求,那么只需要添加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()。请使用以下语句:

$(document).ajaxSend(function(event, jqXHR, ajaxOptions) {
    jqXHR.setRequestHeader('my-custom-header', 'my-value');
});

不使用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;

你可以使用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();