Error: Retrieving the token using Vue Cookies method returns a null value

My development project involves the use of vuex, axios, vue-cookies, and JWTs. I have a specific file named api.js that is imported into the main Vue JS file. Below is the code snippet from api.js:

import axios from 'axios'
import Vue from 'vue'
import { store } from "@/store";

export default axios.create({
    baseURL: store.state.endpoints.baseUrl,
    headers: {
        Authorization: `JWT ${Vue.$cookies.get('token')}`,
        'Accept': 'application/json',
        'Content-Type': 'application/json'
    }
})

Upon logging in through the login page, everything seems to be successful. The cookie 'token' value updates correctly with the new token in the browser inspector, Vuex indicates that the user is authenticated, and the router redirects me to the homepage. However, when attempting to navigate to a page on the homepage that requires authentication, the header passes 'JWT null' instead of the actual token from the cookie, leading to a failure and trapping me in a loop of successful login but inability to proceed.

If I log in and then refresh the page before doing anything else, everything functions as expected and the JWT is no longer null. It seems like the issue lies in the api.js code mentioned earlier not properly retrieving the token from the cookie each time it is called, but only upon page refresh. Could this be due to caching or do I need to somehow reload this import after logging in?

For additional context, here's a snippet of code from my login page showcasing how the data is updated post-login:

  api.post(this.$store.state.endpoints.obtainJWT, payload)
      .then((response) => {
        console.log("Token - "+response.data.token);
        console.log("Profile - "+response.data.user);
        this.$cookies.set('token', response.data.token);
        this.$store.commit("setAuthUser",
            {authUser: response.data, isAuthenticated: true})
      })
      .then(() => this.$router.push({path: '/'}))
      .catch((error) => {
        console.log("Error!");
        console.log(error);
        console.debug(error);
        console.dir(error);
      })

Here's an example of an API call that displays 'JWT null' if accessed before refreshing the page:

import api from "../api.js";
...
api.get("/data_full/" + id)
  .then((response) => {
    this.title = response.data.title;
  })

Lastly, in my project's main.js file, I have the import for api.js:

...
import api from './api.js'
...
Vue.$http = api;

Answer №1

After posting my question and reviewing it, I had a moment of clarity. The issue wasn't with the get('token') call, but rather with the fact that I was creating an Axios instance that was not being recreated after saving a token to a cookie.

I made the decision to transfer code related to the authorization header from api.js to main.js as an interceptor. Now, every time an Axios call is made, the token value in the cookie is fetched automatically. This change effectively resolved the problems I was encountering. See the updated code in main.js below;

    ...
    api.interceptors.response.use(
        config => {
            const token = Vue.$cookies.get('token');
            if ( token != null ) {
                config.headers.Authorization = `JWT ${token}`;
            }
            return config
        },
    ...

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

I am unable to modify the view page in CodeIgniter

I'm encountering difficulties when attempting to modify the view page within my code. Please note that I am utilizing AJAX. Within the controller function known as "insert_inventario", after saving information in the array_db, it undergoes a comparis ...

Using Angular to Bind JSON Data

I'm currently in the process of evaluating different JS frameworks for a project and I find myself torn between Angular and Ember. As I continue to explore Angular, I have a specific question regarding data binding to an external json file stored on S ...

"Troubleshooting when a NodeJS Program Refuses to

Currently facing an issue while attempting to execute a Node program written in JavaScript with no indication of what's causing the problem. The program abruptly ends without providing any error or stack trace. const prompt = require('prompt-sync ...

What's the reason for not being able to customize classes for a disabled element in Material-UI?

Currently, I am utilizing Material-UI to style my components. However, I am facing challenges when trying to customize the label class for disabled buttons. Despite setting a reference as "&$disabled", it does not yield the desired results. import Rea ...

The system is unable to show real-time data at the moment due to an error message being returned: {"error": "'QuerySet' object has no attribute 'body'"}

I am looking to integrate real-time data display in a Django application using Ajax. My goal is to allow users to see what they are typing as they type it, and I am achieving this by utilizing Django's JsonResponse with the following method: def get_ ...

Expand the grid with extra rows once it has been generated, especially when dealing with a large volume of database records, utilizing JQGrid or JSGrid

Having a large dataset (json) that takes too long to display in the grid for users, I'm looking for a solution. My idea is to initially run a filtered query (e.g. records from the current year) to quickly build the grid. Once the grid is presented to ...

The socket io server connection triggers repeatedly

Currently, I am working on developing a simple game using next.js and node.js. However, when I test the game, I notice that there are multiple "connected" logs being displayed. Even though I have only one client (with just a single tab open in Chrome), the ...

Do not pay attention to any external styles when working within the component

Whenever I integrate my Vue component into a pre-existing page that has global input element styles applied, I encounter issues with these styles affecting the elements within my component. Is there a way for the component to ignore these stylesheets unl ...

What is the reason that the subscribe method is not invoked immediately after applying the groupBy operator

Why isn't the subscribe method of the second example being triggered? All logs within the pipe are functioning correctly in both examples. WORKING EXAMPLE: (although using hardcoded data and a different creator): of([ {tableName: 'table1&apo ...

Safari showing white flash upon setting background-image src using Intersection Observer?

I've done extensive research but I'm still struggling to solve this issue. It only seems to be happening on Safari (Mac & iOS), while everything works smoothly on Chrome, Firefox, Edge, and other browsers. UPDATE: The flickering problem also per ...

Acquire the id_token from Google using oauth2

I am currently working with AngularJS on the client side and trying to implement Google OAuth2. While I have successfully obtained the access token, I now need to retrieve the ID token. In order to achieve this, I have made modifications in app.js, contro ...

How can I remove the script file from my req.params?

Can anyone help me figure out how to extract the :rid from my req.params without getting two values, one being the rid and the other the script file? Take a look at this screenshot from the console.log: console.log picture This is my route code: router. ...

Tips for switching the status of each item as I navigate the page with the tab key

I am facing an issue with my list of items that have hidden content appearing on hover. I want to achieve the same functionality while tabbing through my page, but currently, all hidden content appears at once. Check out a live example of my code here jQ ...

Choosing an option in Vue using select, v-for loop, and v-model

How can I set a preselected option in a select element using v-model, v-for for options, and an object as the value? The options are elements with unique ids, and I want to preselect based on custom equality (e.g., matching the id field). Is there a way to ...

An error has occurred in Angular5 and Three.js: 'Scene1' property is undefined

Running into an issue with my angular5 website integrated with Three.js. I keep getting an error message that says: Cannot read property 'Scene1' of undefined when trying to add an object to the Scene. Any suggestions on how to properly define th ...

Creating a dynamic JSTree that loads data on demand using Stored Procedures

Currently in my SQL Server database, I have two Stored Procedures that are responsible for extracting data from a tree structure: One procedure retrieves all nodes at a specific level based on the provided level number. The other procedure retrieves th ...

Increasing Engagement with Dynamic Page Titles in AngularJS Application

We are currently developing a large AngularJS/NodeJS application and have encountered an issue regarding page titles. In our application, we aim to have dynamic page titles for each state using ui-router. We can add custom fields to states such as pageTitl ...

Redirecting to a specified URL after submitting a POST request in Angular

I recently started learning Angular and decided to follow this tutorial on creating a MailChimp submission form. I made sure to customize the list information & id according to my own needs. However, after submitting the form, I encountered an issue wh ...

In VueJS and Quasar, what is the best way to retrieve the clicked item in order to pass it to the API?

Utilizing a codepen sample with local data, I am hoping it will work for troubleshooting purposes. However, in reality, I am using vuex and an API endpoint to source the data. Unfortunately, I cannot share the API details. The core functionality involves ...

Creating a Clickable Column in a React Table: A Step-by-Step Guide

I am utilizing React Table (React Bootstrap Table-2) to exhibit a table on a page and populate it with data retrieved from a database API. My objective is to convert the values shown in one of the columns into clickable links (hrefs). This specific column ...