Jenssen
Jenssen

Reputation: 1881

Axios request interceptor is not working in my vue app

I'm trying to make axios working with a request interceptor. However before a request is made the interceptor is not triggered. What could be going wrong here? I've red already a lot about this problem but not found a solution so far. Could use some help here! This is my code:

    import VueRouter from 'vue-router';
    import Login from './components/Login.vue'
    import Home from './components/Home.vue'
    import axios from 'axios';

    window.Vue = require('vue');
    
    window.axios = axios.create({
        baseURL: 'http://localhost:8080',
        timeout: 10000,
        params: {} // do not remove this, its added to add params later in the config
    });
    
    
    Vue.use(VueRouter);
    
    // Check the user's auth status when the app starts
    // auth.checkAuth()
    
    
    const routes = [
        { path: '/', component: Login, name: 'login' },
        { path: '/home', component: Home, name: 'home', beforeEnter: requireAuth },
    ];
    
    const router = new VueRouter({
        routes // short for `routes: routes`
    });
    
    const app = new Vue({
        router
    }).$mount('#app');
    
    function requireAuth (to, from, next) {
        if (!loggedIn()) {
            router.push('/');
        } else {
            next()
        }
    }
    
    function loggedIn() {
        return localStorage.token !== undefined;
    }
    
    
    axios.interceptors.request.use(function (config) {
       alert('test');
    
        return config;
    }, function (error) {
        // Do something with request error
        return Promise.reject(error)
    })

When I use axios within another vue file:

    axios.get('users').then((data) => {
                    console.log(data);
                });

The interceptor is not triggered!

Upvotes: 14

Views: 29914

Answers (2)

Philip Feldmann
Philip Feldmann

Reputation: 8435

You're calling the interceptor on the axios instance you imported, but it needs to be on the instances you created.

Calling window.axios = axios.create() is really bad style anyway and you should avoid it at all costs. If you want it to be globally available you should bind it to the Vue Prototype. Even better would be to move it out in another module:

const instance = axios.create({
    baseURL: 'http://localhost:8080',
    timeout: 10000,
    params: {} // do not remove this, its added to add params later in the config
});

instance.interceptors.request.use(function (config) {
   alert('test');

    return config;
}, function (error) {
    // Do something with request error
    return Promise.reject(error)
})

export default instance

If you really want it to be available everywhere without having to import it, consider wrapping my code from above inside a Vue plugin and let your Vue instance use it, as shown here in the 4. comment.

Upvotes: 51

Pallavi
Pallavi

Reputation: 1

axios.interceptors.response.use(async function (response) {
    return response;
}, async function (error) {
    if (error.response.status === 401) {
        //call your api for refresh token
        error.config.headers[
            "Authorization"
        ] = `bearer ${token from your result}`;
        return axios(error.config);
    }
    return Promise.reject(error);
});

By using above code you can automatically call the current api url.

Upvotes: 0

Related Questions