Implementing Axios interceptor is a common practice in Vue.js applications to central

Hello everyone, I'm facing a problem with the interceptor in VueJS. I can't seem to figure out where the issue lies and it's driving me crazy...

I've gone through various tutorials and read numerous posts on stackoverflow, but everything still seems unclear to me.

When I add a debugger, it works fine, but as soon as I switch to "axios.interceptors" it gives me an error saying axios is undefined, which is puzzling...

import axios from 'axios';

debugger;
axios.interceptors.response.use(function (response) {
    console.log(response);
    // Any status code that falls within the range of 2xx causes 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);
});

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

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

The above code is used 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({commit}) {
            Http.get('/customers').then(result => {
                commit('SET_CUSTOMERS', result.data.data );
            }).catch(error => {
                throw new Error(`API ${error}`);
            });
        }
    }
};

I am trying to detect HTTP status code 401 to log out the user and delete the token from the browser.

If anyone has any insights or solutions, I would greatly appreciate your help. Thank you so much.

Best regards, Christophe

Answer №1

In the guidelines for interceptors provided in the documentation, it is mentioned that after defining the interceptors example, you must include the interceptor within an instance:

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);
    // Execute specific actions with response data for status codes in the 2xx range
    return response;
}, function (error) {
    console.log(error);
    // Handle response errors for status codes outside the 2xx range
    return Promise.reject(error);
});
export default instance;

Answer №2

If you're curious about how the problem was resolved, here is the code I used:

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)
}

Next step is to add this to main.js

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

Create api.js which acts as my client for all requests, ensuring they pass through it.

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 trust this will be of use to you :)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Effortlessly sending multiple values from text fields using jQuery

i am using jQuery to fetch all values from text fields with the same field name. $('input[name^="StudentName"]').each(function() { StudentName += $(this).val(); alert(StudentName); }); when I alert, all the values are displayed as one s ...

Please ensure that the menu is included within the HTML file

How can I include a menu from menu.html into index.html? The content of menu.html is: <li><a href="home.html">Home</a></li> <li><a href="news.html">News</a></li> In index.html, the code is: <!docty ...

What is the best method for emptying the input of Vuetify's v-autocomplete using the #clear slot?

Currently, I am working with a <v-autocomplete> component that I would like to make clearable. By simply setting the clearable attribute, it does work. However, I have a specific custom icon component that I wish to use instead of the default clear i ...

Reset input fields while retaining placeholder text

Seeking advice on how to use this handy jQuery tool properly: $('.myDiv input').each(function () { $(this).val(""); }); Though it clears my form, I'm struggling to maintain the placeholders of the inputs. Any suggestions? C ...

Utilize the power of AJAX for efficiently sorting search results retrieved from MySQL

I'm in the process of designing a flight search page. The initial page contains a form, and when the submit button is clicked, the search results are displayed on the second page. Here's the link to the first page: To test it out, please follow ...

Show/hide functionality for 3 input fields based on radio button selection

I need assistance with a form that involves 2 radio buttons. When one radio button is selected, I want to display 3 text boxes and hide them when the other radio button is chosen. Below is the code snippet: These are the 2 radio buttons: <input type= ...

Using jQuery to dynamically retrieve a radio button

After struggling with this issue for quite some time, I have come to the realization that it's too complex for me to handle on my own. I could really use some assistance here. The problem at hand involves a page displaying various products, each of w ...

"Error: Unable to access the property '$emit' of an undefined value" - VueJS

I'm currently working on implementing a basic authentication system in vuejs. I have a set of objects containing valid usernames and passwords. I am looping through this list to validate the entered username and password. If there is a match, I trigge ...

The pug blend fails to produce the desired output

Recently, I've encountered an issue while working with Pug in a Vue.js application. The task at hand is to create a multi-level menu (with submenus) using the provided data structure: mounted () { this.catalog = [ { title: "Компр ...

js TouchEvent: When performing a pinch gesture with two fingers and lifting one of them up, how can you determine which finger was lifted?

I am currently working on a challenging touching gesture and have encountered the following issue: let cachedStartTouches: TouchList; let cachedMoveTouches: TouchList; function onStart(ev: TouchEvent) { // length equals 2 when two fingers pinch start ...

Excessive requests to location or history APIs in a brief period of time

Alert: Reached maximum update depth. This issue may arise when a component invokes setState within useEffect without a dependency array, or if any of the dependencies change on each render. const OwnerPage = () => { const onOpen = useAgencyModal((s ...

What is the reason behind JavaScript subtracting the timezone offset for ISO dates when passed into the Date() function?

In my function, I handle different valid date strings to produce a JavaScript Date object. Most strings work as expected, however, when an ISO formatted date (YYYY/MM/DD) is provided, the user's timezone offset is deducted from the date. For example ...

The issue of conflicting clickability between Vue row and href

Apologies for the confusion. I am dealing with an unusual question here. In my table setup, each row can be clicked using the iWasClicked function. However, the last column contains clickable images (href links), and I only want the images to be clickabl ...

Show the contents of a JSON file using Vue

I have a JSON file containing some data that needs to be fetched and displayed in a component. In the actions of my Vuex store, I've implemented: async getTodos (context) { const todos = [] const response = await fetch('../../data/todos.jso ...

How to efficiently target and manipulate links using jQuery Mobile

I previously asked a question about loading an external page without ajax while maintaining it as an iOS web app window. In that example, I used the following code: <script> $(document).bind('pageinit', function() { $("#test").click(func ...

Strategies for passing a JavaScript variable to a JSP function

I'm dealing with a JavaScript code that has a value stored in its variable that I need to pass to my JSP function. However, I'm facing trouble passing it along. Take a look at the following code snippets: Javascript: $('button').on(& ...

Adjust the color of the active link on the page using Angular and CSS

I have a project that I need to modify by adding a sub menu that appears on every page but is only coded once. My goal is to highlight the link for the current page, all within one HTML snippet. Although the list renders correctly, I'm struggling to g ...

Utilizing Parent Scope Variables in AngularJS Directives with Isolated Scopes

I'm feeling a bit lost here (edit: after clarification, my question is "Why isn't the directive recognizing the attributes passed to it?"), even though I thought I had a good grasp on it. I'm having trouble accessing the properties of the pa ...

Computed Property Output Remains Static in Template Usage (Vue3 sans Composition API)

I need to retrieve the width of an item in order to pass it as a CSS variable within a computed property. <div class="wrapper"> <fieldset> <legend :style="`--gap:${legendGap}px`"></legend> </fieldset&g ...

Displaying Data in Table Using Ajax Request

I'm working on a project that involves creating an HTML table from an ajax request pulling SharePoint list items. The screenshot provided demonstrates how it functions and what it displays after the button is clicked. However, I am looking for a way t ...