Axios请求拦截器等待ajax调用完成

2024-03-25

我有一个用于 axios 调用的请求拦截器。它检查我的 jwt 令牌并在必要时调用刷新。

axios.interceptors.request.use((config) =>{

    const state = store.getState(); // get renewed state
    const time = Math.floor( new Date().getTime() / 1000 );

    if( 
        ! state.app.jwtRefreshOnRequest 
        && time >= state.jwt.expires - 120
        && state.jwt.refresh_before > time
    ){ // expiring in 2 min. refresh    

        //dispatch({type: 'JWT_REFRESH_REQUEST'});
        axios.get( API_BASE_URL + '/auth/refresh')
            .then(function(response){
                // dispatch({type: 'JWT_REFRESH_SUCCESS', payload: response.data});
                axios(config).then(resolve, reject);
            })
            .catch(function(err){               
                reject(err);
        });

    }       

    return config;
}); 

此代码正确调用刷新并保存新令牌,但原始调用在拦截器请求完成之前不会保留,因此使用过期的令牌。

所以,我想我需要从拦截器进行同步调用。


避免对 HTTP 请求进行同步调用,因为它们只会使您的应用程序挂起。

这里您需要做的是使调用代码异步 - 与回调、promise 或异步相关的任何内容的一般规则是,一旦异步,所有内容都需要异步。

Here, axios.get返回一个Promise- 跟踪异步 HTTP 请求并在完成后解析的对象。你需要返回它,而不是config.

我们通过返回一个新的来做到这一点Promise- 如果需要新令牌的 HTTP 请求,它会等待,如果不需要,它可以resolve立即地。

axios.interceptors.request.use(config =>
    new Promise((resolve, reject) => {
        // ... your code ...

        axios.get( API_BASE_URL + '/auth/refresh')
            .then(response => {
                // Get your config from the response
                const newConfig = getConfigFromResponse(response);

                // Resolve the promise
                resolve(newConfig);
            }, reject);

        // Or when you don't need an HTTP request just resolve
        resolve(config);
    })
}); 

每当你看到那个then你正在处理Promise,一旦你是一切需要返回一个Promise.

This is much如果你可以使用的话会更容易async/await- 现代浏览器支持的新关键字,如果您需要支持旧用户,则可以转译。有了这些你就可以把Promise内联调用await关键词。

axios.interceptors.request.use(async config =>

    // ... your code ...

    if(/* We need to get the async token */) {
        const response = await axios.get( API_BASE_URL + '/auth/refresh');
        config = getConfigFromResponse(response);
    }

    return config;
}); 
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Axios请求拦截器等待ajax调用完成 的相关文章

随机推荐