Refresh Vue module when router is pushed

Hello everyone! I'm new to Vue.js and have encountered an issue with my api module. The code looks like this:

axios.create({
  baseURL: URL,
  headers: {
    Authorization: 'Bearer ${localStorage.getItem('token')}'
  }
})

When on the login page without a token, the module is already loaded as it's used for the login request. After a successful login, I update the token using

localStorage.setItem('token', token)
. However, the api module doesn't reflect this change until I manually refresh the browser page, causing my requests to have a null token until then.

How can this issue be resolved?

Initially, I considered forcing a page reload after login by switching from this.$router.push('/') to this.$router.go('/'), but this broke the navigation to the index page.

I would greatly appreciate any suggestions or solutions. Thank you.

Answer №1

If you're looking for a way to manage your API service with axios in Vue.js, one approach is to wrap it in a plugin. Here's an example implementation:

Make sure to explicitly set the token in your axios instance each time you initialize it.

ApiService.js

const axios = require('axios');

// Function to create an axios instance.
const axiosFactory = (options) => axios.create({
    ...options,
    headers: {
        Authorization: `Bearer ${localStorage.getItem('token')}`,
    }
});

// To set the token in axios and save it in localStorage
const setTokenFactory = (axios) => (token) => {
    localStorage.item('token', token);
    axios.defaults.headers.common['Authorization'] = `Bearer ${token}`;
}

// Vue plugin to set $api to axios and expose a setToken function in Vue.
const install = (Vue, axios) => {
    Vue.mixin({
        setToken: (token) => {
            setTokenFactory(Vue.protoype.$api)(token);
        }
    });
    Vue.prototype.$api = axios;
}

// Create an axios instance
const api = axiosFactory({
    baseURL: /* URL */
});
const setToken = setTokenFactory(api);
module.exports = {
    api,
    setToken,
    plugin: {
        install
    }
};

In your main.js

const ApiService = require('./ApiService');
Vue.use(ApiService.plugin, ApiService.api);

To utilize the api outside of Vue, simply import it like this:

const { api, setToken } = require('./ApiService');

api.get();
setToken(token);

When working within Vue, access axios using this.$api. To set the token upon user login, rely on the setToken function such as this.setToken(token)

Answer №2

Upon logging in, users have the option to manually set their token. They can choose to retrieve the token from the login response and set it themselves, or request the token from a different API call.

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

Troubleshooting 404 errors on Firebase hosting with dynamic routes

My next.js app is deployed on firebase. The app has been deployed and in use for some time now. I created a dynamic route page Redeployed the app While I could access the dynamic page via a router, I encountered a 404 page not found error upon refreshing ...

jQuery radio button for mobile devices

I'm currently working on a web application using jQuery 1.9.1 and jQuery Mobile 1.3.2. One issue I'm facing involves horizontal radio buttons that display an icon: data-icon="radio-on". These radio buttons are dynamically added to the DOM. Her ...

use element ui tree and vue to filter files according to selected folder

Utilizing the element UI treeview to showcase folders. Each folder or its child folder contains files that need to be displayed based on folder selection. While it's easy to filter and list out these files in a normal list, I am facing challenges with ...

The password prompt window refuses to align with the center of the screen. This

I've been struggling to position the Javascript popup notification using the width, height, top, and left parameters in the window.open function. No matter what I attempt, it stubbornly remains in the top-left corner. Can someone offer some guidance o ...

Is the absolute positioned element on the left or right based on its current location?

Is there a way to assign absolute positioning with left at 0px or right at 0px depending on whether the positioned div will go outside of its container? For example, when you right click in a browser and see the menu appear to the right of where you click ...

Tips for implementing draggable elements using JavaScript and React hooks, creating a more interactive user experience

I'm working on a project where I need to incorporate draggable divs, each corresponding to an image in an array of images, into a container. The current implementation seems to function properly, but there's an issue - the dragging action only w ...

The Datalabels in Sunburst Highchart are being concealed outside of the svg container

Within the Sunburst highchart, I have positioned the data labels outside the circle using x and y coordinates. dataLabels: { y: -75, rotation: 0, x: -15 } However, if I assign a specific value to the x or y axis (e.g. y: -110) and the labels extend ...

Retrieve the most recent information based on the ID from an object by utilizing timestamps within Angular 6

I have an array of objects stored in the 'component' variable component=[{id:1,date:'20-10-2020'},{id:1,date:'13-01-2020'},{id:2,date:'30-03-2020'}] Within this array, there are 2 objects with the same 'id&apos ...

Tips for creating a concise switch statement in JavaScript, incorporating both the use of Express and Mongoose

Here's the current situation: I am tasked with searching in 3 different databases for an ID associated with a shift. Each shift is classified as either an Activity, Food and Beverages, or Other type. When making the search, the type is provided in t ...

What is the best way to change JSON into a string format?

Similar Question: Converting JavaScript Object to JSON String I am dealing with a JSON object in JavaScript and I need to change it into a string. Is there a specific function I should use for this conversion? Appreciate any assistance, ...

Eliminate all blank spaces at the top and bottom of Span by squishing it

Imagine I have this code snippet: <span class="labels" style="background-color: #FFFFFF;border: 1px solid #000000;font-family: Verdana;font-size: 11px; ">74.58 ft.</span> I am looking for a way to compress the span element so that only the te ...

How to utilize Javascript to open a new view in ASP.NET MVC

Transitioning my thought process from WebForms to MVC, I am looking to achieve the following tasks: 1) Trigger a button click event that will 2) run some JavaScript code in order to 3) open a new browser window or tab displaying an existing view from the ...

What is the process for adding submitted data to an already-existing local JSON file?

I have a new Angular assignment that requires me to push form data into an existing JSON file locally. The task is to develop an Angular application where users can create new tasks and view them on a separate page. Initially, I attempted using http.post ...

Ways to determine if an array with a mix of data types includes string values

Challenge I'm Currently Tackling: To solve this challenge, create a function named "findShortestWordAmongMixedElements". The task is to find and return the shortest string from an array that contains mixed element types. Important Notes: * In c ...

The plus sign ('+') fails to be matched by the regular expression in Angular 2, although it functions correctly in other testing environments

Check out this code snippet: export const PASSWORD_PATTERN: RegExp = /^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])[a-zA-Z0-9`~!@#$%^&*()\-_+={[}\]|\\:;"'<,>.?/]{8,}$/; This constant is utilized in the following manner elsewhere: ...

Error: the search variable is not defined

function sorting(type) { $("#parentDiv").empty(); $.getJSON("example_data.json", ({ Find })); function Locate(a, b) { return (a[Find.type] < b[Find.type]) ? -1 : (a[Find.type] > b[Find.type]) ? 1 : 0; }; } The example_data.j ...

Tips for incorporating conditional statements within return statements in functional components in React JS

I need to display the login page if the user is not logged in, otherwise show the forbidden 403 page. Since I'm using a functional component, I can't use render(). return forbidden === false ? ( <> <Container maxWidth="x ...

When it comes to using the text() function, the statement encounters difficulty

let person = $(".tekst").text(); if (person=="XxX") { $("#discu").css("display", "none"); } alert(person); When I access my element with class .tekst and get its text using the text() function, it correctly displays as XxX, which is what I expected. ...

How to troubleshoot Path Intellisense in VScode when using jsconfig.json for Next.js

In the structure of my project, it looks like this: jsconfig.json next.config.json components |_atoms |_Button.jsx |_Button.module.scss |_... |_... ... Within the jsconfig.json file, I have specified the following settings: { ...

Iterating through an object results in a false outcome

In my project, I am calling a dynamic API to retrieve some values. The JSON returned by this API looks like: {name: "test", resource_group: "group1", location: "westeurope", disk_size: "30 GB", os_type: "Linux", ...} let url const [MachinesRow, setMachin ...