【问题标题】:Prevent ajax request till new token is obtained阻止ajax请求直到获得新令牌
【发布时间】:2017-04-28 08:26:18
【问题描述】:

我已经为我的 WEB API 实现了刷新令牌功能,因此用户可以使用刷新令牌获取新令牌。

每当 API 返回未经授权的状态代码时,我都需要获取新令牌并使用该新令牌更新所有待处理的请求。但取而代之的是,一些 ajax 请求使用旧令牌发送 API 请求,因为新令牌尚未获得,新令牌的请求正在进行中。

我想要一种方法来阻止这个请求,直到没有获得新的令牌。另外,我使用了第三方 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 jquery ajax


    【解决方案1】:

    在服务器生成新令牌之前,使用以下代码在特定时间内使用您的 javascript。

    function wait(ms) {
        var start = new Date().getTime();
        var end = start;
        while (end < start + ms) {
            end = new Date().getTime();
        }
    }
    

    等待(5000); //5 秒

    在等待功能中,您可以指定服务器生成令牌所花费的时间。如果对您有帮助,请投票。

    【讨论】:

    • 这没什么用,因为所有请求都是异步发送到 API 的,我想在获取第一个请求回调并且授权失败时阻止它们。
    猜你喜欢
    • 1970-01-01
    • 2019-11-04
    • 1970-01-01
    • 1970-01-01
    • 2018-07-29
    • 2018-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多