Axios interceptor refresh token for multiple requests

房东的猫 提交于 2020-12-30 03:22:15

问题


I'll throw the http request because I'm calling the refresh token when it returns 401. After the refresh token response, I need to throw the previous request

SAMPLE Logın -> — 1 hours later— —> call product —> 401 —> call refresh token —> call product

I try this link a link and look this link a link but doesn't work.

Catch the 401 error

setInterceptors = () => {
        axios.interceptors.response.use(
            response => {
                return response;
            },
            err => {
                return new Promise((resolve, reject) => {
                    if (err.response.status === 401 && err.config && !err.config.__isRetryRequest) {

                        const originalRequest = err.config;

                        this.emit('onAutoLogin', originalRequest);
                    }
                    // throw err;
                });
            }
        );
    };

Call my action

jwtService.on('onAutoLogin', originalRequest => {
                    jwtService
                        .signInWithToken()
                        .then(res => {
                            if (res.access_token) {
                                originalRequest.headers['Authorization'] = 'Bearer ' + res.access_token;


Axios.request(originalRequest).then(response => {
                                    store.dispatch({
                                        type: ** MY PROBLEM İS HERE **
                                        payload: response.data
                                    });
                                });
                            }
                        })
                        .catch(err => {
                            jwtService.setSession(null); 
});

回答1:


using this link I was able to solve the problem without triggering the redux store.

let isRefreshing = false;
 let failedQueue = [];

       const processQueue = (error, token = null) => {
            failedQueue.forEach(prom => {
                if (error) {
                    prom.reject(error);
                } else {
                    prom.resolve(token);
                }
            });

            failedQueue = [];
        };

axios.interceptors.response.use(
            response => {
                return response;
            },
err => {
                const originalRequest = err.config;

                if (err.response.status === 401 && !originalRequest._retry) {
                    if (isRefreshing) {
                        return new Promise(function(resolve, reject) {
                            failedQueue.push({ resolve, reject });
                        })
                            .then(token => {
                                originalRequest.headers['Authorization'] = 'Bearer ' + token;
                                return axios(originalRequest);
                            })
                            .catch(err => {
                                return Promise.reject(err);
                            });
                    }

                    originalRequest._retry = true;
                    isRefreshing = true;

                    return new Promise(function(resolve, reject) {
                        axios
                            .post('/fooUrl/refreshToken', {
                                refreshToken: "fooToken"})
                            .then(({ data }) => {
                                axios.defaults.headers.common['Authorization'] = 'Bearer ' + data.fooToken;
                                originalRequest.headers['Authorization'] = 'Bearer ' + data.fooToken;
                                processQueue(null, data.fooToken);
                                resolve(axios(originalRequest));
                            })
                            .catch(err => {
                                processQueue(err, null);
                                store.dispatch(showMessage({ message: 'Expired Token' }));

                                reject(err);
                            })
                            .then(() => {
                                isRefreshing = false;
                            });
                    });
                }

                return Promise.reject(err);
            }
        );


来源:https://stackoverflow.com/questions/57890667/axios-interceptor-refresh-token-for-multiple-requests

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!