My function is not getting called in javascript/vue

时间:2019-01-09 21:55:51

标签: javascript vue.js vuejs2

I'm currently having problems with my code not calling a function in javascript. I am trying to call a function to refresh my JWT token but for some reason, it is not calling it at all.

I have added multiple debugging texts to see where it is able to run and for some reason, it will not call the function.

This is the function which is not being called. The console will never print 'Test 2 passed'

function refreshToken(store) {
    console.log('Test 2 passed'); //This doesnt get displayed in the console
    if(store.state.auth.isRefreshing) {
        return store.state.auth.refreshingCall;
    }

    console.log('Test 3 passed');
    store.commit('setIsRefreshing', true);
    const refreshingCall = window.axios.get('/api/user/refresh-token').then(token => {
        console.log('Test 4 passed');
        originalRequest['Authorization'] = 'Bearer ' + token;
        store.commit('setIsRefreshing', false);
        store.commit('setRefreshingCall', undefined);
        console.log('Token has been updated to: '+ JSON.stringify(token));
        localStorage.setItem('token', token);
        window.axios.defaults.headers.common['Authorization'] = 'Bearer '+ token;
        store.commit('setToken', token);
        console.log('Test 5 passed');

        return Promise.resolve(originalRequest);
    });

    store.commit('setRefreshingCall', refreshingCall);
    return refreshingCall;
}

This is the axios interceptor which will detect of the page returns a 401 so it can call the refresh token function

window.axios.interceptors.response.use(function (response) {
    // Do something with response data
    return response;
}, function (error) {
    let res = error.response;
    if (res.status === 401 && res.config && !res.config.__isRetryRequest) {
    // Do something with response error
        alert("You're login session expired. Please log in again.")
        console.log('Test 1 passed'); //This gets displayed in the console
        var ret = refreshToken(this.store).then(__ => {
            error.config.headers['Authorization'] = 'Bearer ' + store.state.token;
            error.config.baseURL = undefined;
            console.log('I have ran the last part: '+ store.state.token);
            console.log('Test 6 passed');
            return window.axios.request(error.config);
        });

        return ret;
    }


    return Promise.reject(error);
});

I can't seem to find why the function is not getting called, any ideas?

(Image of the console)

enter image description here

0 个答案:

没有答案