Javascript 我可以为所有 AJAX 请求设置全局标头吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14527360/
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 17:06:12  来源:igfitidea点击:

Can I set a global header for all AJAX requests?

javascriptjqueryajaxheader

提问by Trip

This doesn't seem to be working :

这似乎不起作用:

$.ajaxSetup({
  headers: {
    Accept: 'application/vvv.website+json;version=1 ',
    Authorization: 'Token token=\"FuHCLyY46\"'
  }
});

I would have thought it would. If I add these filters specifically to my AJAX call then they do work. I'd like to do this globally for all AJAX calls.

我本来以为会的。如果我将这些过滤器专门添加到我的 AJAX 调用中,那么它们就会起作用。我想为所有 AJAX 调用全局执行此操作。

回答by John Koerner

I did some additional tests and the code you posted works perfectly. If you have problems with something in how the parameters are setup, you could always to go the beforeSend call and modify the xml request yourself.

我做了一些额外的测试,你发布的代码运行良好。如果您在设置参数方面遇到问题,您可以随时调用 beforeSend 并自己修改 xml 请求。

$.ajaxSetup({
    beforeSend: function (xhr)
    {
       xhr.setRequestHeader("Accept","application/vvv.website+json;version=1");
       xhr.setRequestHeader("Authorization","Token token=\"FuHCLyY46\"");        
    }
});

回答by Daniel

It's also possible to do this in a framework-agnostic way by monkey-patching the open method:

也可以通过猴子修补 open 方法以与框架无关的方式执行此操作:

var o = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function(){
  var res = o.apply(this, arguments);
  var err = new Error();
  this.setRequestHeader('X-Ajax-Stack', JSON.stringify(err.stack));
  return res;
}

In this example I'm sending stack trace information via a header, which allows the backend to know where Ajax requests originated, even if it's from third-party code that doesn't use jQuery.

在此示例中,我通过标头发送堆栈跟踪信息,这允许后端知道 Ajax 请求的来源,即使它来自不使用 jQuery 的第三方代码。

(Note: careful about headers getting too big)

(注意:小心标题 变得太大

回答by Trip

The beforeSendanswer does not establish the same header's as adding headerdirectly to the ajax call. So in order for jQuery to do this properly I add this :

beforeSend回答没有建立相同header的如添加header直接到Ajax调用。因此,为了让 jQuery 正确执行此操作,我添加了以下内容:

headers: myGlobalHeaders

where myGlobalHeadersis a global variable. Unfortunately, I have to write this extra line on every single ajax call. Terrible! Maybe I'll edit the jQuery framework to handle this..

哪里myGlobalHeaders是全局变量。不幸的是,我必须在每次 ajax 调用时多写一行。糟糕的!也许我会编辑 jQuery 框架来处理这个..