Ensure that the token remains current with each axios operation

I need to access an Express REST API that demands a valid json web token for certain routes. In order to include the token from localstorage every time I needed, I had to create an "Axios config file".

My http.js file includes the code below:

import Vue from "vue";
import axios from "axios";

const devInstance = createInstance("http://localhost:3000");

devInstance.interceptors.request.use(config => {
    console.log(config);
    return config;
}, err => {
    console.log(err);
    return Promise.reject(err);
});

devInstance.interceptors.response.use(res => {
    console.log(res);
    return res;
}, err => {
    console.log(err);
    return Promise.reject(err);
});

const productionInstance = createInstance("http://www.myApi.com");

function createInstance(baseURL){
    return axios.create({
        baseURL,
        headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${localStorage.token}`
        }
    });
}

Vue.prototype.$http = devInstance; // Check debug/build mode

In my main.js, I import this instance once:

import http from "./http.js";

and now I can use this.$http to access the global axios instance without having to import it again.

However, when trying to consume the API, localStorage.token returns undefined because it is not set during instance creation.

Is there a way to automatically update the Authorization attribute without manually passing the token each time?

Answer №1

Consider implementing a request interceptor that automatically includes the Authorization header in all outgoing requests.

devInstance.interceptors.request.use((config) => {
    config.headers.Authorization = `Bearer ${localStorage.token}`;
    return config;
}, (error) => Promise.reject(error));

By doing this, you can ensure that the token stored locally is always utilized.

Answer №2

To improve the functionality of the Authorization field, consider implementing a timer and an asynchronous update. This could be achieved by creating a separate component dedicated to handling this task, or by incorporating a timer and async method within the existing component (although compatibility with Vue may need to be verified).

I trust this suggestion proves beneficial. Best regards

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

When there is no content in the responseText, AJAX will display an error

I've encountered an issue while trying to fetch data using AJAX. The problem lies in receiving an empty responseText. Here's the code I'm working with: JavaScript: function getFounder(id) { var founder = ""; $.ajax({ ...

When configuring lint-staged, a file is created that includes a unique identifier with details on the packages that have been

When starting a new Vue project, I use npm init vue@latest and select all options (including Eslint with Prettier). For this setup, I am on Windows 11 with node v17.4 and npm v8.4. After creating the project via PowerShell, I switch to Visual Studio Code ...

Tips for accessing the initial value within JSON curly braces

In my code, there is a function that returns the following: { 'random_string': '' } The value of random_string is an unknown id until it is returned. How can I extract this value in JavaScript? Appreciate any help. Thanks. ...

Displaying or concealing an input field in vue.js depending on the selection of a radio button

I am currently working on customizing a pre-built form in Vue.js, where certain inputs are displayed or hidden based on the selection of two radio buttons: <b-form-group label-class="ssrv-form-control"> <div class="ssrv-5"& ...

AssistanceBubble.js with ASP.NET UpdatePanel

Looking for guidance on implementing HelpBalloon.js () within an ASP.NET UpdatePanel. Experiencing issues with image loss after a postback. ...

Leveraging a variable in Python for XPATH in Selenium

I have a variable that looks like this: client_Id = driver.execute_script("return getCurrentClientId()") I want to update the XPATH by replacing the last value (after clientid=2227885) with the client_Id variable. So: prog_note = wait.until(EC.p ...

exploring various dynamic elements using jquery

If you need some help figuring this out, take a look at the JSFiddle here. I've set it up for users to input any data they want in the text box, choose a table from set one, and then click the "submit" button to send it. <div> <Div> < ...

Verifying the "select" dropdown option prior to final submission

My website features multiple select dropdowns that require validation before submission. For instance, there may be a situation where seven select dropdowns are present as described below. My desired validation criteria is: If there are 5 or more "sel ...

React Ant Design: Encountered a warning for 2 elements having non-unique properties

I have incorporated the Carousel component, with each one containing a different component. One contains a form, while the other includes an external library component called react-input-otp. https://codesandbox.io/s/pensive-einstein-uucvm?fontsize=14& ...

Redirecting to password reset page from S3 static web hosting

I'm facing an issue with my static website hosted on S3. My application is supposed to send a mail containing a link to reset a password. However, when I click on the link, instead of being directed to the password reset page, I receive an error messa ...

Customizing the CSS of the TinyMCE editor within a React application

Incorporating TinyMCE 5 into my React project has been an interesting challenge. I'm looking to personalize the editor by adjusting elements like borders and adding box shadows to the toolbar. Despite attempting to add CSS through the content_css prop ...

Beginning the deployment of a Nuxt SSR application on Azure with the build files

According to the Nuxt documentation, running yarn build will result in Nuxt.js creating a .nuxt directory containing everything ready for deployment on your server hosting. After reviewing a couple of other guides, it appears that additional items require ...

The functionality of the combobox in Vuetify differs from that of an input field

I have implemented Vuetify and am using its combobox component for search functionality on my website. However, I have noticed that the text value in the combobox only gets added to the watcher when the mouse exits the field. This behavior is not ideal f ...

Discovering the nearest sibling using jQuery

My HTML code snippet is as follows: $(".remove-post").click((event) => { $(event.target).fadeOut(); } <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="side-bar"> <b ...

What is the best way to ensure that a navbar dropdown appears above all other elements on

I'm having trouble creating a navbar dropdown with material design. The dropdown is working fine, but the issue I'm facing is that other elements are floating above it. https://i.stack.imgur.com/aJ0BH.png What I want is for the dropdown to floa ...

Capturing user inputs in PHP or AJAX

Is there a way to capture keystrokes on a web page regardless of where the user is focused? For example, if someone has the webpage open and they press '1', can it trigger an action? And if they press '2', can something else happen wit ...

Issue: Unable to create the restangular module because: the variable '_' is not defined

Upon integrating Restangular into an existing website, I encountered a JavaScript error that stated: Failed to instantiate module restangular due to: '_' is undefined I'm unsure of what this means. Can anyone clarify why '_' is ...

The function to navigate, 'navTo', is not defined and so it cannot be read

I am trying to create a navigation button in my SAPUI5 application deployed on Fiori _onPageNavButtonPress: function () { var oHistory = History.getInstance(); var sPreviousHash = oHistory.getPreviousHash(); if (sPreviousHash !== ...

Is localStorage.getItem() method in NextJS components behaving differently?

I'm working on my nextjs application and I wanted to utilize the power of localstorage for storing important data throughout my app. Within the pages directory, specifically in the [slug].tsx file, I implemented the following logic: export default fu ...

Exploring Angular's capabilities with filtering and handling $http promises

Having an issue with filtering data from a JSON file that contains an array of 20 objects. Within my factory, I have implemented two functions: function fetchData() { return $http .get('mock.json') .success(_handleData) ...