Javascript 如何使用 js 或 jQuery 向 ajax 请求添加自定义 HTTP 标头?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7686827/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 03:11:06  来源:igfitidea点击:

How can I add a custom HTTP header to ajax request with js or jQuery?

javascriptjqueryajaxhttp-headershttprequest

提问by Txugo

Does anyone know how to add or create a custom HTTP header using JavaScript or jQuery?

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

回答by Prestaul

There are several solutions depending on what you need...

根据您的需要,有多种解决方案...

If you want to add a custom header (or set of headers) to an individual requestthen just add the headersproperty:

如果要将自定义标头(或标头集)添加到单个请求,则只需添加headers属性:

// Request with custom header
$.ajax({
    url: 'foo/bar',
    headers: { 'x-my-custom-header': 'some value' }
});

If you want to add a default header (or set of headers) to every requestthen use $.ajaxSetup():

如果要向每个请求添加默认标头(或标头集),请使用$.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' } });

If you want to add a header (or set of headers) to every requestthen use the beforeSendhook with $.ajaxSetup():

如果您想向每个请求添加一个标头(或一组标头),请使用beforeSend带有$.ajaxSetup()以下内容的钩子:

$.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' } });

Edit (more info):One thing to be aware of is that with ajaxSetupyou can only define one set of default headers and you can only define one beforeSend. If you call ajaxSetupmultiple times, only the last set of headers will be sent and only the last before-send callback will execute.

编辑(更多信息):要注意的一件事是,ajaxSetup您只能定义一组默认标头,并且只能定义一个beforeSend. 如果您ajaxSetup多次调用,则只会发送最后一组标头,并且只会执行最后一个发送前回调。

回答by Szilard Muzsi

Or, if you want to send the custom header for every future request, then you could use the following:

或者,如果您想为以后的每个请求发送自定义标头,则可以使用以下内容:

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

This way every future ajax request will contain the custom header, unless explicitly overridden by the options of the request. You can find more info on ajaxSetuphere

这样,每个未来的 ajax 请求都将包含自定义标头,除非被请求的选项明确覆盖。你可以在这里找到更多信息ajaxSetup

回答by Jayendra

Assuming JQuery ajax, you can add custom headers like -

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

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

回答by James

Here's an example using XHR2:

这是使用 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++;
}; 

Hope that helps.

希望有帮助。

If you create your object, you can use the setRequestHeader function to assign a name, and a value before you send the request.

如果您创建对象,则可以在发送请求之前使用 setRequestHeader 函数分配名称和值。

回答by Roland T.

You can also do this without using jQuery. Override XMLHttpRequest's send method and add the header there:

您也可以在不使用 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;

回答by Stefan D.

You should avoid the usage of $.ajaxSetup()as described in the docs. Use the following instead:

您应该避免使用docs 中$.ajaxSetup()描述的。请改用以下内容:

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

回答by Quentin

Assuming that you mean "When using ajax" and "An HTTP Requestheader", then use the headersproperty in the object you pass to ajax()

假设您的意思是“使用 ajax 时”和“一个 HTTP请求标头”,然后使用headers您传递给的对象中的属性ajax()

headers(added 1.5)

Default: {}

A map of additional header key/value pairs to send along with the request. This setting is set before the beforeSend function is called; therefore, any values in the headers setting can be overwritten from within the beforeSend function.

标题(添加 1.5)

默认: {}

与请求一起发送的附加标头键/值对的映射。此设置在调用 beforeSend 函数之前设置;因此,headers 设置中的任何值都可以从 beforeSend 函数中被覆盖。

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

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

回答by 4esn0k

"setRequestHeader" method of XMLHttpRequest object should be used

应该使用 XMLHttpRequest 对象的“setRequestHeader”方法

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

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

回答by Kamil Kie?czewski

You can use js fetch

您可以使用 js获取

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();