[英]Ajax HTTP request interceptor, adding a header value after upon promise.resolve is not working
我正在嘗試通過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'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
oauth.getCurrentToken()基本上是我所擁有的服務,它將從localStorage檢索令牌對象后解析該令牌對象。
我需要在解析之前執行getCurrentToken()的原因是因為該值可能會不時更改,所以我需要始終解析最新的令牌
問題是beforeSend
是同步的,所以promise then()
在請求發送之前不會觸發
您可能需要創建自己的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))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.