【问题标题】:Kendo UI datasource - beforeSend with async/awaitKendo UI 数据源 - beforeSend 与 async/await
【发布时间】:2020-05-14 03:45:33
【问题描述】:

最初我在 kendo UI 数据源的 beforeSend 事件中使用 setRequestHeader() 在 http 标头中设置熊令牌,效果很好。

现在,为了处理令牌超时问题,我想在 beforeSend 事件中刷新令牌。但是因为 Fetch 是一个异步函数,所以 beforeSend 事件会立即返回,所以 kendo 数据源使用旧令牌,然后最终得到 401。

我检查了 beforeSend 不支持异步,所以任何想法都可以实现这个目的?

更新

按照建议,我使用了ajaxSend(),每次调用 ajax 时都会调用它。 在 ajaxSend() 内部,我使用 fetch(跨域)刷新令牌,以便下一次 ajax 调用将在请求标头中使用新令牌:

$(document).ajaxSend(function (e, xhr, options) {
    console.log('Event: ', e);
    console.log('xhr: ', xhr);
    console.log('Options: ', options);

    console.log('Old access_token: ', my_user.access_token);

    let formData = 'grant_type=refresh_token&refresh_token=' + my_user.refresh_token;

    fetch('url/Token', {    //---cross domain server
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded'},
        body: formData })
    .then(data => data.json())
    .then(user => {
        if (user.access_token) {
            xhr.setRequestHeader('Authorization', 'Bearer ' + user.access_token);

            console.log('New access_token: ', user.access_token);
        }
        else {
            console.error('error');
        }
    }).catch(error => {
        console.error(error.message);
    })
});

但奇怪的是,不知道为什么接下来的ajax调用仍然使用'Old access_token'而不是'New access_token'

第二次更新

我发现ajaxSend 也不支持异步。

还有一个帖子跟我有同样的问题。 jQuery: how to make ajaxSend wait for another Ajax response before proceeding?

该帖子中的答案建议不要让原始 ajax 请求等待,另一种方法是中止原始请求并在异步调用(我的是 fetch)完成后重试请求。 我以前有这样的想法,但它不适合我的情况,因为我使用 Kendo UI 网格等待响应,然后网格将自动更新。如果我中止原始请求并重试,Kendo UI 网格将不会自动更新,因为请求已中止。除非我手动通过代码更新剑道网格,但这不是我的意图。

【问题讨论】:

    标签: async-await kendo-ui bearer-token kendo-datasource


    【解决方案1】:

    你可以尝试用ajaxSend拦截请求。

    $(document).ajaxSend(function (e, xhr, options) {
        console.log('Event: ', e);
        console.log('xhr: ', xhr);
        console.log('Options: ', options);
    
        xhr.setRequestHeader('Authorization', 'Bearer ' + 'jwt');
    });
    

    这将拦截每个请求。我用readfetch dataSource 方法对其进行了测试。

    .ajaxSend()

    注意:从 jQuery 1.8 版本开始,此方法只能附加到文档。

    【讨论】:

    • 感谢您的回答。我按照您的建议使用 ajaxSend()。请参阅我的问题的更新部分。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2013-09-03
    • 1970-01-01
    • 2018-10-18
    • 2017-05-05
    • 2012-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多