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


当前回答

使用XMLHttpRequest对象的“setRequestHeader”方法

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

其他回答

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

你可以使用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 ajax,您可以添加自定义标题,如-

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

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

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

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