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

Is it possible to remove a particular div after clicking the delete button, especially if multiple divs are displayed upon clicking the add

var count = 2; var countMax = 5; function adddt() { if (count > countMax) return; document.getElementById('dt-' + count + '').style.display = 'block'; count++; } <link href="https://maxcdn.bootstrapcdn.com/bo ...

Having issues with closing a div tag using $.after() function

This issue can be better understood with an example: http://jsbin.com/lavonexuse The challenge here is to insert a full-width row after a specific column (identified by the class .insertion-point) when "Insert Row" is clicked. The problem I'm facing ...

Basic example of jQuery in an ASPX file

I can't figure out why this basic example is not working. In my WebApplication, I have a script: function myAlert() { $("#Button1").click(function () { alert("Hello world!"); }); } In my asp page, I have the following code: < ...

Point the direction to nextjs and react native expo web

I am currently working on redirecting a URL to another within my website, specifically in Next.js and Expo React Native Web. While I don't have an actual "About" page, I do have other pages nested under the "about" folder and am aiming to direct any ...

I am having issues with my code because I am trying to call a method on the root from within a component

I'm working on a bootstrap modal component that includes a button labeled "Got It". I'm trying to call a method on the root instance when this button is clicked, but it's not working as expected. I've added a click handler and emitted t ...

Guide to creating a synchronous wrapper for jQuery ajax methods

I've made the decision to switch from synchronous ajax calls to asynchronous ones due to lack of support in most modern browsers. My code is currently reliant on synchronous (and dynamic) ajax calls to client-side functions that must be completed befo ...

The Azure-hosted Node.js web application is not displaying any content

I followed a tutorial on deploying my Vue project on Azure, but I encountered an issue. Even though the main.ts file exists in the app service, the hosted URL is showing an error and can't find the main.ts file. Here is a screenshot of the error: Erro ...

I need help accessing data from a REST API and displaying it in a table

How can I call all the data in "md" and display it in a table? I've tried multiple values but none seem to work. Can someone guide me on how to use the "md" value to display in a table? <script src="https://ajax.googleapis.com/ajax/libs/jquery/ ...

Struggling to establish a consistent header on every page in AngularJS

I've been attempting to implement a header that appears on all my pages using AngularJS. Here is the current setup I have: In my HTML file, I've included the following code: <html ng-app="webApp"> <script src="/vendor/angular.min.js"& ...

Having difficulties generating a vue-web-extension using vue-cli

Currently, I am in the process of enhancing a chrome extension by adding a new popup page developed in Vue. The tutorial I am referring to for this task can be found at . However, when attempting the step vue init kocal/vue-web-extension my-extension, I e ...

How can I edit this code in JSPDF to print two pages instead of just one?

Currently, I have a script that can generate a PDF from one DIV, but now I need to create a two-page PDF from two separate DIVs. How can I modify the existing code to achieve this? The first DIV is identified as #pdf-one and the second DIV is #pdf-two. p ...

Is it possible to spread an empty array in JavaScript?

Whenever I run the code below, I encounter the error message Uncaught SyntaxError: expected expression, got '...': [1,2,3, (true ? 4 : ...[])] I'm wondering if spreading an empty array in that manner is allowed? ...

Load the flexslider once the fancybox container is opened

In my experience, I have found flexslider and fancybox to be very useful plugins. Individually, they work perfectly fine on a website that I am currently working on. However, when I tried placing a flexslider gallery inside a fancybox div, I encountered a ...

How can we add styles to text entered into a form input field in a targeted way?

Is there a way to apply styling to the second word entered into a form input text field after the user hits "enter" and the data is output? In this scenario, the text always follows the format of 3 numbers, followed by a space, and then a name. For examp ...

The process of matching the full names of the source and destination Strings in Node.js

Need assistance comparing two strings with a third string in a JSON Array for full names var source = intentObj.slots.toPlazaName.value.toString(); // Jaipur var destination = intentObj.slots.fromPlazaName.value.toString(); // Kishangarh Compare with t ...

Utilizing Node.js to Retrieve a POST Request JSON and Modify its Format

Received an incoming Post request in JSON format like this: [{"username":"ali","hair_color":"brown","height":1.2},{"username":"marc","hair_color":"blue","height":1.4},{"username":"zehua","hair_color":"black","height":1.8}] Need to transform it into the f ...

Set a Vue.js variable when the input value changes

Hey there, I'm having trouble with a form that I need to complete using Vue.JS. Basically, I want the value of the 'price_vat' field to update with some calculations every time the 'price_user' input is updated. Everything was work ...

Angularjs application and bash script generating different SHA256 hashes for the same file

In my AngularJS app, I am struggling to get the digest of an uploaded file. The issue is that the resulting hash is not matching the one obtained using bash locally. Initially, I used jshashes, but when I noticed discrepancies in the hashes generated by t ...

Leveraging the package.json file to execute a separate script within the package.json file

Within my project's package.json file, I have a script called npm run script1. Additionally, my project includes a private npm package as a dependency, which contains its own set of scripts in its package.json file, including one named script2. My goa ...

Tips on retrieving 'captureDate' from data points and dispatching it as a notification

Currently, I am working on adding a new feature to my discord bot that will allow it to collect the user's most recent gameclip. While I am able to gather all the necessary information in my console log, I am finding it challenging to figure out how t ...