Javascript Ajax HTTP请求拦截器,在OnPromise.resolve之后添加头值无效
我试图通过ajax拦截器解析HTTP请求中的授权头Javascript Ajax HTTP请求拦截器,在OnPromise.resolve之后添加头值无效,javascript,jquery,ajax,http,http-headers,Javascript,Jquery,Ajax,Http,Http Headers,我试图通过ajax拦截器解析HTTP请求中的授权头 $.ajaxSetup({ beforeSend: function (xhr) { oauth.getCurrentToken().then((token) => { console.log(token); // gets logged for all my requests xhr.setRequestHeader('x-my-custom-header2', 'test2'); // doesn'
$.ajaxSetup({
beforeSend: function (xhr) {
oauth.getCurrentToken().then((token) => {
console.log(token); // gets logged for all my requests
xhr.setRequestHeader('x-my-custom-header2', 'test2'); // doesn't work
});
xhr.setRequestHeader('x-my-custom-header', 'test1'); // work
}
});
但是,我可以看到x-my-custom-header被添加到我的请求中,而x-my-custom-header2没有
Provisional headers are shown
Accept: */*
Referer: http://localhost:3000/
Sec-Fetch-Mode: cors
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36
x-my-custom-header: test1
getCurrentToken()基本上是我拥有的一个服务,它将在从localStorage检索令牌对象后解析它
我需要在解析之前执行getCurrentToken()的原因是,因为值可能会不时更改,所以我需要始终解析最新的令牌问题在于
在发送前
是同步的,因此在发送请求之前不会触发承诺然后()
您可能需要创建自己的ajax服务函数,以便在创建请求选项之前解析getCurrentToken()
比如:
function doAjax(url, data, type = 'get') {
return oauth.getCurrentToken().then((token) => {
return $.ajax({
url,
data,
type,
beforeSend: (xhr) => xhr.setRequestHeader('x-my-custom-header2', token);
});
});
}
// usage
doAjax('somePath', {foo:'bar'}, 'post').then(res=> console.log(res))
有没有一种方法可以使用异步的全局ajax设置?还有一个问题,如果我想将一个对象作为一个参数传递,以保存我们可以使用的其他属性,该怎么办?例如processData、contentType等。。。另外,也不清楚为什么要使用url、数据、类型来保存值no?您的意思是url:url、数据:数据、类型:类型吗?这些属性在ES6结构化中是允许的,但与
url:url
相同,这对于完全支持浏览器更安全。您可以有一个options
参数,并执行类似const opts=$.extend({beforeSend:(xhr)…},options)
<代码>返回$.ajax(opts)