我已经为我的 WEB API 实现了刷新 token 功能,因此用户可以使用刷新 token 获取新 token 。
每当 API 返回未经授权的状态代码时,我都需要获取新 token 并使用该新 token 更新所有待处理的请求。但取而代之的是,一些ajax请求使用旧 token 发送API请求,因为尚未获取新 token 并且新 token 的请求正在进行中。
我想要一种方法来阻止此请求,直到未获得新 token 为止。另外,我使用了第三方 javascript 库,因此我无法将 async 设置为 false,因为这会损害系统的性能。
更新:
通过添加以下逻辑解决了该问题。希望这可以帮助其他人。
$.ajaxPrefilter(function (opts, originalOpts, jqXHR) {
// you could pass this option in on a "retry" so that it doesn't
// get all recursive on you.
if (opts.refreshRequest) {
return;
}
// our own deferred object to handle done/fail callbacks
var dfd = $.Deferred();
// if the request works, return normally
jqXHR.done(dfd.resolve);
// if the request fails, do something else
// yet still resolve
jqXHR.fail(function () {
var args = Array.prototype.slice.call(arguments);
if (jqXHR.status === 401) {
$.ajax({
url: BASEPATH.APIPATH + '/Token',
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'
},
method: 'POST',
refreshRequest: true,
error: function () {
// reject with the original 401 data and then redirect to login page.
setTimeout(function () {
window.location = "/Login";
}, 4000);
dfd.rejectWith(jqXHR, args);
},
success: function (res) {
// retry with a copied originalOpts with new access token.
var newOpts = $.extend({}, originalOpts, { url: opts.url });
// pass this one on to our deferred pass or fail.
$.ajax(newOpts).then(dfd.resolve, dfd.reject);
}
});
} else {
dfd.rejectWith(jqXHR, args);
}
})
return dfd.promise(jqXHR);});
最佳答案
将您的 JavaScript 与以下代码结合指定时间,直到服务器生成新 token 。
function wait(ms) {
var start = new Date().getTime();
var end = start;
while (end < start + ms) {
end = new Date().getTime();
}
}
等待(5000);//5秒
在wait函数中,您可以指定服务器生成 token 所需的时间。如果对您有帮助,请投票。
关于javascript - 阻止ajax请求,直到获得新 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41118347/