admin管理员组

文章数量:1323330

Good evening everyone, here I have a problem with my interceptor in VueJS. I don't understand where my problem es from, and I'm pulling my hair out...

I've watched several tutorials, I've watched several topics on stackoverflow, but I don't understand what's going on at all.

When I put a debugger on, it's triggered, but when I switch to "axios.interceptors" it tells me that axios is undefined, it's inprehensible...

import axios from 'axios';

debugger;
axios.interceptors.response.use(function (response) {
    console.log(response);
    // Any status code that lie within the range of 2xx cause this function to trigger
    // Do something with response data
    return response;
}, function (error) {
    console.log(error);
    // Any status codes that falls outside the range of 2xx cause this function to trigger
    // Do something with response error
    return Promise.reject(error);
});

const token = localStorage.getItem('token');

export default axios.create({
    baseURL: process.env.VUE_APP_URL_API,
    headers: {
        Authorization: `Bearer ${token}`
    }
})

The code above is called in my VueX Store.

import Http from "../../api/http";

export default {
    state: {
        customers: {},
        customer: {},
    },
    getters: {
        customers: state => state.customers,
    },
    mutations: {
        SET_CUSTOMERS(state, customers) {
            state.customers = customers;
        }
    },
    actions: {
        loadCustomers({mit}) {
            Http.get('/customers').then(result => {
                mit('SET_CUSTOMERS', result.data.data );
            }).catch(error => {
                throw new Error(`API ${error}`);
            });
        }
    }
};

I want to trigger http code 401 to logout my user and destroy the token in the browser.

If anyone could help me, I would be delighted, thank you very much.

Regards, Christophe

Good evening everyone, here I have a problem with my interceptor in VueJS. I don't understand where my problem es from, and I'm pulling my hair out...

I've watched several tutorials, I've watched several topics on stackoverflow, but I don't understand what's going on at all.

When I put a debugger on, it's triggered, but when I switch to "axios.interceptors" it tells me that axios is undefined, it's inprehensible...

import axios from 'axios';

debugger;
axios.interceptors.response.use(function (response) {
    console.log(response);
    // Any status code that lie within the range of 2xx cause this function to trigger
    // Do something with response data
    return response;
}, function (error) {
    console.log(error);
    // Any status codes that falls outside the range of 2xx cause this function to trigger
    // Do something with response error
    return Promise.reject(error);
});

const token = localStorage.getItem('token');

export default axios.create({
    baseURL: process.env.VUE_APP_URL_API,
    headers: {
        Authorization: `Bearer ${token}`
    }
})

The code above is called in my VueX Store.

import Http from "../../api/http";

export default {
    state: {
        customers: {},
        customer: {},
    },
    getters: {
        customers: state => state.customers,
    },
    mutations: {
        SET_CUSTOMERS(state, customers) {
            state.customers = customers;
        }
    },
    actions: {
        loadCustomers({mit}) {
            Http.get('/customers').then(result => {
                mit('SET_CUSTOMERS', result.data.data );
            }).catch(error => {
                throw new Error(`API ${error}`);
            });
        }
    }
};

I want to trigger http code 401 to logout my user and destroy the token in the browser.

If anyone could help me, I would be delighted, thank you very much.

Regards, Christophe

Share edited Feb 6, 2021 at 22:19 Dan 63.2k18 gold badges110 silver badges119 bronze badges asked Feb 6, 2021 at 21:19 ChristopheChristophe 3991 gold badge6 silver badges23 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4

As shown in the interceptor docs, just below the example interceptors, if you use an instance, you have to add the interceptor to it:

import axios from 'axios';

const token = localStorage.getItem('token');

const instance = axios.create({
    baseURL: process.env.VUE_APP_URL_API,
    headers: {
        Authorization: `Bearer ${token}`
    }
})

instance.interceptors.response.use(function (response) {
    console.log(response);
    // Any status code within the range of 2xx cause this function to trigger
    // Do something with response data
    return response;
}, function (error) {
    console.log(error);
    // Any status codes outside the range of 2xx cause this function to trigger
    // Do something with response error
    return Promise.reject(error);
});

export default instance;

For people which are wondering how the issue has been solved, there is my code :)

success.js

export default function (response) {
    return response
}

failure.js import router from 'vue-router'

export default function (error) {
    switch (error.response.status) {
        case 401:
            localStorage.removeItem('jwt.token')

            router.push({
                name: 'Login'
            })
            break
    }

    return Promise.reject(error)
}

adding this to main.js

const token = localStorage.getItem('jwt.token')
if (token) {
    axios.defaults.headers.mon.Authorization = token
}

create api.js which is my client for all the request, so my request are always passing by this.

import axios from 'axios'
import success from '@/interceptors/response/success'
import failure from '@/interceptors/response/failure'

const api = axios.create({
    baseURL: process.env.VUE_APP_URL_API
})

api.interceptors.request.use((config) => {
    const token = localStorage.getItem('jwt.token')

    config.headers.Authorization = `Bearer ${token}`

    return config
})

api.interceptors.response.use(success, failure)

export default api

I hope it will be usefull :)

本文标签: javascriptVuejsExport an axios interceptorStack Overflow