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

Encountering issues while deploying a Vue.js application on an Ubuntu server using GitLab Runner

Currently, I am in the process of deploying an application from a GitLab repository to a server running Ubuntu 20.04. The GitLab runner is registered and operational, with all SSH keys added accordingly. Although I have created the .gitlab-ci.yml file, I e ...

Unlocking the Power of Session Variables in AngularJS using Ui-router

Currently, I am utilizing Angular to manage routes. On the server side, Passport is being used so that I can access the user session variable req.user in my views. However, when dealing with a route rendered by ui-router, my req.user ends up being undefine ...

Pressing the Enter key will result in data fetched from JSON being logged multiple times

I am currently implementing a search feature on my React website. When a user enters a keyword in the search input, the keyword is matched in a JSON file. If a match is found, it logs "yes" to the console; otherwise, nothing is logged. Here is an example ...

Fixing Cross-Browser Issues with the OnScroll Function

window.onscroll = function() { if( window.XMLHttpRequest ) { var bodyId=document.getElementById('bodymain'); if (bodyId.scrollTop > 187) { //make some div's position fixed } else { //mak ...

What is the best way to retrieve app.state in a Remix project when running a Cypress test?

One way Cypress can expose an app's state to the test runner is by using the following approach in React: class MyComponent extends React.Component { constructor (props) { super(props) // only expose the app during E2E tests if (window.C ...

Read through the text, determine the length of each word, and keep track of how

Objective: Create a JavaScript program that takes input from users in the form of several lines of text and generates a table displaying the count of one-letter words, two-letter words, three-letter words, etc. present in the text. Below is an example ou ...

Equivalent of ResolveUrl for loading scripts without the need for server technology

I am in the process of converting an ASP.NET web page into a plain HTML web page. Most of the work is done, however, I am having trouble replacing the ASP.NET Page.ResolveUrl function when setting a reference to a javascript file: <script src="<%= ...

Leverage Angular to highlight updated items within a list

My goal is to synchronize data, so I have a data object that holds the current state. Whenever this state changes, I want to mark the object with an attribute for filtering purposes during syncing. Here is the structure of the object: data = { type1: [ ...

Ways to confirm non-null values and bypass the row if it is

I have been attempting to compare 2 dates in order to appropriately display data in a table. I have tried the following approach: ${this.dateToCompare.getTime()} > ${row.CreateDate.getTime()} However, there is an issue where CreateDate has a null value ...

What is the process of embedding base64 encoded data into an image in Javascript after retrieving the data from Azure Blob Storage?

I am attempting to insert an image by utilizing the base64 data pattern, rather than a URL link. Initially, I retrieve the data from Azure Blob storage using the Azure Node.js SDK: Azure Node.js SDK After downloading the data as a string, I am unsure of ...

What is the simplest way to send an AJAX request to run a PHP script?

Hey everyone, I'm facing a specific issue on my website that I haven't been able to solve by searching online. Therefore, I decided to create this question myself. What I'm trying to achieve: When I click a button on my site, it triggers a ...

Troubleshooting JavaScript in Internet Explorer 9

Currently, I am encountering an issue while attempting to debug JavaScript .js files in my Solution using Visual Studio 2010 and IE 9. Despite placing breakpoints in the files, I am unable to debug successfully. I have attempted various troubleshooting ste ...

Is there a way to retrieve information from a different object?

Access the code on Plunker I am working with two data structures - ingredients and recipes [{ "id":"1", "name": "Cucumber" }, .. ] and [{ "id":"1", "name": "Salad1", "recipein":[1, 3, 5] }, { ... } ] My goal is to ...

What is the best way to post an image using nodejs and express?

Recently, I've been working on a CMS for a food automation system and one feature I want to incorporate is the ability to upload pictures of different foods: <form method="post" enctype="multipart/form-data" action="/upload"> <td>< ...

JavaScript codes within HTML elements may not be functional when using an AJAX loader to transition to the next page

I'm experiencing issues with an ajax loader in Wordpress. The theme I am using has an ajax loader button that is interfering with my inline script. Despite reading over 10 articles on the problem, I haven't been able to find a solution yet. Do ...

What is the best way to prompt Leaflet to refresh the map display?

I'm facing a challenge while integrating Leaflet with React, where Leaflet seems to want control over the DOM rendering as well based on my research. Currently, I have countries being properly colored according to specific color codes derived from ba ...

Tips for updating the left positioning of a Div element on the fly

Although my title may not fully explain my goal, I am dealing with dynamically created div elements. When a user triggers an ajax request to delete one of the divs, I want to remove it from the DOM upon success. The issue arises in adjusting the layout aft ...

Retrieve the ultimate content of a text field when a key is pressed, only if the click action is permitted to proceed

Is there a method to prevent users from entering certain characters into a text box based on the resulting text in the textbox? One possible approach is outlined below: <input type="text" id="test" /> document.getElementById(&qu ...

Issue with jQuery .hover() not functioning as expected

The issue I'm encountering is just as described in the title. The code functions correctly on all divs except for one! $(".complete-wrapper-1").hide(); var panelHH = $(".file-select-wrapper").innerHeight; $(".files-button").hover(function(){ $(" ...

Adjust the speed of the remaining divs below to move up when one is deleted using Ajax and jQuery

My div elements are arranged from top to bottom, and when one selected div is removed or faded out, all other divs below it shift up suddenly to fill the gap. While this behavior is functional, I would prefer to slow down the movement of the divs shifting ...