Various titles utilized in Axios patch requests

After spending an hour exploring the Chrome console, I'm still unable to pinpoint the source of this bug.

I'm in the final stages of updating the OAuth implementation in my Vue app.

It all started when socialLink.js discovered the need to create a new user. The Vue component Vue-authentication relies on the presence of an access_token in the response, so I returned some placeholder text:

return api.sendResponse(res, { email, name, socialId, access_token: 'abcd' });

This generated value is stored in the localStorage:

https://i.stack.imgur.com/RKRaA.png

Upon redirection, the SignUp.vue component is displayed and I fill out the form. The first interaction with the server involves a Vuex call to create a new user:

response = await this.$store.dispatch('CREATE_USER_PROFILE', payload);

This call results in a JWT token being issued:

const token = auth.createToken(userId, nickname, new Date(), null, false, '1m');
return api.sendCreated(res, api.createResponse(token));

Which I then store on the Vue page:

const { data } = response;
const token = data.data;
if (token === undefined) {
  this.error = this.$t('sign-up.something-went-wrong');
  return false;
}

I verified that the token matches what was received from the server:

Request URL: https://beta.mezinamiridici.cz/api/v1/users
Request Method: POST
Status Code: 201 Created

{"success":true,"data":"eyJhbGciOiJIUzI1NiIs...Tl8JFw2HZ3VMXJk"}

Next, I invoke another Vuex method and provide the current JWT token as input:

await this.$store.dispatch('UPDATE_USER_PROFILE', {

Using Vuex devtools, I ensured that the correct JWT token was present. This token was then passed to api.js.

Within api.js, I established an Axios configuration containing an Authorization header:

function getAuthHeader(context, jwt = undefined, upload) {
  const config = { headers: { } };
  if (jwt || (context && context.rootState.users.userToken)) {
    config.headers.Authorization = `bearer ${jwt || context.rootState.users.userToken}`;
  }

Again, I cross-checked to ensure the proper JWT token was utilized there.

Finally, all the data was passed to Axios:

function patch(endpoint, url, body, context, jwt) {
  const headers = getAuthHeader(context, jwt);
  console.log(headers);
  if (endpoint === 'BFF') {
    return axios.patch(`${VUE_APP_BFF_ENDPOINT}${url}`, body, headers);
  } else {
    return axios.patch(`${VUE_APP_API_ENDPOINT}${url}`, body, headers);
  }
}

I logged this information and confirmed the correct JWT token remained intact:

bearer eyJhbGciOiJIUzI1N....8JFw2HZ3VMXJk

There seems to be no reason for the header to suddenly switch back to abcd, yet, it's evident in the 'Network' tab:

https://i.stack.imgur.com/T0yOK.png

Consequently, the server encounters a parsing error.

Does anyone have insights into why Axios is using a different value for the Authorization header than the one provided?

Answer №1

After some investigation, I have figured out the mystery. It seems that the culprit behind the issue is vue-authenticate. This library creates Axios interceptors and manages the Authorization header on its own.

vue-authenticate.common.js:

var defaultOptions = {
  bindRequestInterceptor: function ($auth) {
    var tokenHeader = $auth.options.tokenHeader;

    $auth.$http.interceptors.request.use(function (config) {
      if ($auth.isAuthenticated()) {
        config.headers[tokenHeader] = [
          $auth.options.tokenType, $auth.getToken()
        ].join(' ');
      } else {
        delete config.headers[tokenHeader];
      }
      return config
    });
  },

Since my code is more intricate and deals with internal accounts using email/password, this piece of code is causing conflicts. The interceptor needs to be a present and operational function. To resolve this, I made the following modifications:

Vue.use(VueAuthenticate, {
  tokenName: 'jwt',
  baseUrl: process.env.VUE_APP_API_ENDPOINT,
  storageType: 'localStorage',
  bindRequestInterceptor() {},
  bindResponseInterceptor() {},
  providers: {
    facebook: {
      clientId: process.env.VUE_APP_FACEBOOK_CLIENT_ID,
      redirectUri: process.env.VUE_APP_FACEBOOK_REDIRECT_URI,
    },

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

Discovering alterations in current value rather than simply OnChange using nuxt and vuetify

Due to export default { name: "Details", async asyncData({ redirect, params, store }) { if ( !store I am providing multiple values, including return { camera: c, thumbnail_url: thumbnail_url, The camera value is being populated ...

What is the best way to bundle a .js file containing code with the export default syntax?

I have a single .js file with the following code: export default (vueInst, obj, events) => { for (const eventName of events) { ... } } An issue has occurred: Error at Function.missingTransform in /node_modules/buble/dist/buble.cjs.js:376:9 T ...

The Discord.js script fails to send embedded messages as intended

Issue with sending embedded messages using Discord.js code Embed code not functioning properly: Error code received: ...

The Vue router fails to load when using create-vue@3

I've been experimenting with the Vue Router, but it's not giving me the expected outcome. While following the tutorial on https://router.vuejs.org/guide/, I found that if I use the CDN and place it in a standalone HTML file, it works fine. Howev ...

Remove dynamically created elements from an AngularJS div

Is there a way to remove an item from the criteria list when clicking the delete button? Currently, only the filter is being refreshed and not the tables. Any suggestions on how to resolve this issue? HTML <ul class="list-unstyled"> <l ...

Transforming a JSON into a JavaScript object using deserialization

Within a Java server application, there exists a string that can be accessed through AJAX. The structure of this string is exemplified below: var json = [{ "adjacencies": [ { "nodeTo": "graphnode2", "nodeFrom": "graphnode1" ...

Prerender is running independently of the dynamic page title and meta tags rendering process

As part of a POC, I was integrating prerender.io with an angular-node application for SEO purposes. My application can be found HERE. The good news is that all three links are being crawled successfully, as confirmed by receiving a 200 OK status for all li ...

A method for integrating a Child Component into a UI5 parent application without specifying them in the manifest.json

Seeking advice on loading a Child Component in a UI5 parent app. Currently working on creating a Fiori Launchpad that can dynamically load other apps as Child Components. I have been exploring methods mentioned in an insightful post at However, the imple ...

Using AJAX to inject JSON data from PHP into Edge Animate

For a school assignment, I am currently working on a project using edge animate. My objective is to import data from a database hosted on my school's webspace and incorporate it into the edge animate project. Despite researching online for a solution ...

What steps should I take to ensure a Vue 2/Vuetify form does not submit if the mandatory fields are left blank?

I developed a contact form using Vue 2/Vuetify 2 for a project I am working on. The form successfully submits to Strapi, the CMS that I am utilizing. However, despite having set rules and validation, it still submits with empty fields. The best progress I ...

Can you explain the function of "app.router" in the context of Express.js?

When looking at the default app.js file generated by express.js, I came across the following line: ... app.use(app.router); ... This particular line of code has left me perplexed for a couple of reasons. First, upon consulting the express api documentati ...

Identifying and capturing changes in child scope events or properties in Angular

I am encountering an issue with my form directive where I need to intercept ng-click events nested within varying child scopes of the form element. However, I am struggling to hook into these events or child scope properties in a generic way. For demonstr ...

Unable to retrieve content using the query.ID in Next.js

I'm trying to figure out what is causing the issue in this code, but I can't seem to resolve it. My goal is to use the query.id inside getInitialProps to fetch some content. The fetching process works fine, but when an error occurs, I receive thi ...

What could be causing this Angular controller to throw the error message "Error: Unknown provider: nProvider <- n"?

Check out the jsFiddle code here: <div ng-app=""> <div ng-controller="FirstCtrl"> <input type="text" ng-model="data.message" /> {{data.message + " world"}} </div> </div> function FirstCtrl($scope) { ...

I often find myself feeling unsure when I incorporate conditional logic in JSX within Next.js

Hello, I am currently using Next.js and encountering an issue with using if/else in JSX. When I use if conditions, the classes of elements do not load correctly. Here is my code: <Nav> { login ? ...

"Enhance your web development skills by mastering jQuery alongside the

It's curious that jQuery doesn't support the use of the "+" sign. You can see how it functions with "1" and "3", but not with "2+". Just hover your mouse over each div to experience it. <div id="div-2+"></div> JSFiddle $('a. ...

Exploring the Seamless Integration of Vuex State with VueRouter in a Nuxt Environment

Hi there, I'm currently trying to access the vuex state from my VueRouter instance but I'm facing some difficulties. When attempting to access the $store property of router.app, it seems to be returning null. This is the code snippet for my Vue ...

Error encountered when asynchronously iterating over an object in TypeScript

Could someone please help me understand why I am getting an error with this code? var promise = new Promise((resolve, reject) => { resolve([1, 2, 3, 4, 5]); }); async function doSomethingAsync() { var data = await promise; data.forEach(v = ...

Navigating to a child route does not maintain the VueX state

I am facing an issue with my child route configuration: {path: '/news/:id', component: () => import('../views/NewsDetail.vue'), props: true }, When I navigate to this route from a different view/component in my app, using ...

Is your WordPress one-page scroll JQuery script failing to function properly?

Currently attempting to develop a single page scroll feature. Within WordPress, my navigation contains anchor tags structured as follows: <a href="#contact">Contact</a> <a href="#about">About</a> The corresponding divs for the li ...