Global Axios Headers Not Functioning Properly in Vue 3 Post-Login

I am currently experiencing an issue with axios login in Vue 3.

Upon successfully logging in and authenticating through the API, I use router.push to redirect the user to the dashboard. Here is the code snippet:

axios.post('auth/signin', {
                username: username,
                password: password
            }).then((response) => {
                localStorage.setItem('accessToken', response.data.accessToken)
                localStorage.setItem('refreshToken', response.data.refreshToken)

                toast.success("Login successful")

                if(VueJwtDecode.decode(localStorage.getItem('accessToken')).sub == "admin"){
                    router.push({name: 'admin.dashboard.index'})
                }else if(VueJwtDecode.decode(localStorage.getItem('accessToken')).sub == "user"){
                    router.push({name: 'user.dashboard.index'})
                }else if(VueJwtDecode.decode(localStorage.getItem('accessToken')).sub == "company"){
                    router.push({name: 'company.dashboard.index'})
                }
            }).catch(error => {
                toast.error(error.response.data.error.message);
            })

The redirection to the dashboard works properly, but the axios header does not function until the page is manually refreshed by pressing F5.

Despite adding the following line in main.js:

axios.defaults.headers['x-access-token'] = localStorage.getItem('accessToken')

How can this issue be resolved? Thank you for your help.

Answer №1

main.js is compiled during the initial booting process, therefore any changes to your axios header should be made when a new access token is received.

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

Is there a way for me to confirm if a node module is compatible with bundling in Webpack and running in a web browser?

One of the advantages of using Webpack is its ability to bundle up node modules for use in an HTML page within a browser. However, not all node modules are compatible for this purpose. Certain modules, such as those utilizing the 'fs' module or n ...

Is it possible for an <input> tag in PHP AJAX to have an "action" attribute similar to a <form> tag?

Forms typically use an action attribute to specify where the data should be posted, such as a .php file. Do <input> elements have this action attribute as well? The answer is likely no, but I am curious to understand what concept I may be misunders ...

Display more/hide less form using div elements in a NextJS project

Looking to create a hidden block of amenities on my hotel website that can be expanded and collapsed with buttons in NextJS using tailwind-css. How can I achieve this functionality? Example 1: https://i.stack.imgur.com/BbrUj.png Example-2: https://i.stac ...

Obtain the following image with every click

I have a div with images inside. I created two arrows (previous, next) within a larger div using the src of one of the images as the background URL for each arrow. My goal is to make the next arrow change the large image to the src of the following image w ...

What is the best way to extract a CSS rule using PHP?

Below is an example of the stylesheet I am currently using: #thing { display: none; } I am looking to retrieve the value of the 'display' property using PHP instead of Javascript. While I know how to do this with Javascript, I would prefer to u ...

Dealing with "Cannot resolve symbol" issue in PhpStorm due to multiple Vue.js projects being installed

Examining the project structure: -node_modules/ ... -package.json -package-json.lock -vue2/ ... -vue3/ -node_modules/ -src/ App.vue main.ts shims-vue.d.ts -package.json -tsconfig.json -webpack.config.js I have successfully installed two diffe ...

Struggling to interpret the array of objects retrieved from a call to UrlFetchApp.fetch in Google App Script

When UrlFetchApp.fetch is called, it provides an array of objects that are stored in the variable 'results': var results = [{"Category 1": "Benefits/Compensatio", "Category 2": "Compensation", "Category 3": "Recognizing You", "Processing Team": ...

Images fail to load when using Vue 3 with webpack 5

Having difficulty displaying images in a Vue 3 project with Webpack 5. The component contains a basic img tag: <template> <div> <img src="./assets/logo.png" /> </div> </template> The project has an src/assets fold ...

Utilizing PHP and JavaScript to Transmit Multiple MySQL Result Sets from a Popup Window

I am attempting to transfer multiple sets of MySQL data through JavaScript from a popup page to the main page. Here is my progress so far: In my popup.php page: $sql = mysql_query("SELECT * from item where category like '$catego ...

Invoke a PHP script using AJAX

I'm following this helpful tutorial on utilizing AJAX to modify a form. Unfortunately, I'm encountering issues with the implementation and finding it challenging to troubleshoot. Here's my current code: Base page <!DOCTYPE html> < ...

A Sophisticated Approach to Implementing a Confirm Password Input in React

I have a new project where I need to include a registration form and ensure that the password and confirm password fields match without needing to click the register button. If the password and confirm password do not match, I also want to display an erro ...

Adding a border to dynamically generated content while excluding the outer borders using CSS - an easy guide

My current project involves establishing a grid system that dynamically populates content, resulting in an uncertain number of elements being created. At the moment, each element is placed within a flexbox container with 3 elements per row. If there are mo ...

jQuery AJAX chained together using promises

In my current project, I am facing an issue where I have 4 get requests being fired simultaneously. Due to using fade effects and the asynchronous nature of these requests, there are times when empty data is received intermittently. To address this issue, ...

Encountering the error message: "Function arguments could not be parsed ()=>"

Here is the code I have written: projectDependencies.forEach((val)=> { container.register(val[0],function () { return require(val[1]); }); }); When I execute the command nodemon server.js, I encounter the following error: Error: c ...

Can access parent refs when exporting a child component with withStyles by following these steps:

For example: Child Component Code // Assume there is a styles object 's' being used in this component class Child extends Component { render() { return ( <h1 ref={(ref)=>{this.ref = ref}}>Hello</h1> ); } } export defau ...

Utilizing the dynamic pairing of Three.js and CSS3 to bring life to animated 3D objects

I am currently working on a project that involves creating 3D Lego elements and assembling them into a figure using animation. I have successfully modeled the elements in Blender and exported them as .obj/mlt files without any issues. However, when it come ...

Establishing connection with SignalR JavaScript client

I'm unfamiliar with SignalR and I find myself feeling lost. My task is to establish a connection to a stream and retrieve certain data. The owner provided some guidance, but they are unsure how to accomplish this using JavaScript. They shared the fol ...

Guide on changing label background color in React

Would you be able to guide me on how to change the background color of the label in react? I am utilizing react + material ui from this source. You can find information on writing CSS in js at this page. Some plugins like jss-nested are available for this ...

Avoid nesting a VirtualizedList component inside a basic ScrollView in React Native to prevent issues

I have come across this question multiple times, and I've gone through all the suggested solutions. Most advise against nesting it inside ScrollView and recommend using SafeAreaView or another alternative instead. However, my scenario is a bit differe ...

Guide on utilizing an NPM package with Vue that mandates the usage of the Node.js filesystem (fs) functionality

Whenever I try to utilize an NPM package in Vue that relies on fs, it consistently fails and throws errors. The error messages usually mention something like "fs could not be resolved" or "fs.readFileSync is not a function". I have come across other sourc ...