Error encountered: AXIOS request failed due to XSRF-TOKEN Mismatch

My server is receiving different X-XSRF-TOKEN headers compared to the cookies being sent when I make requests 2-3 times per second using axios.

let axiosInstance = axios.create({
        baseUrl: "MY_BASE_URL_HERE",
        timeout: 20000
      });
function sendRequest() {
  if (data) {
    if (axiosInstance) {
      axiosInstance
        .post("MY_API_HERE", CryptojsEncrypt(data))
        .then((res) => {
          console.log("success");
        })
        .catch((err) => {
          console.log('error');
        });
    }
  }
}

https://i.sstatic.net/di5Qe.png

I need assistance in ensuring that my requests are sent with consistent cookie values and headers each time.

I attempted to use interceptors and transformRequest to compare the header with the cookie values, and abort the request if they do not match. However, this approach did not work for me. I simply want my requests to have the same headers and cookie values every time they are sent.

Answer №1

It is highly likely due to the simultaneous nature of these inquiries.

Launching a new request before receiving a response from the previous one prevents the second request from accessing the new cookie obtained in the initial response.

Consequently, it may transmit what the server deems an outdated token, but only because your CSRF approach is flawed (further explained below).

Spacing out the requests allows each one to return before the next is initiated, enabling them to occur sequentially and facilitating the exchange of tokens as anticipated by the server (even if incorrectly).

The underlying issue lies in the server-side handling of CSRF. There is no need to generate and send a fresh CSRF token in every XHR/fetch request! Instead, provide a new CSRF token when a non-XHR page request is made. API endpoints should not attempt to set a new CSRF with each call; rather, they should require the existing CSRF stored in the user's session during the API request. This token can remain constant across subsequent XHR/fetch demands unless the user performs a hard browser refresh.

Issuing a new CSRF token for every API request does not enhance security and disrupts parallel XHR/fetch actions from the same user, as evident in your case.

If you have control over the server, addressing this issue there is crucial. Additional details about its setup are necessary for further assistance.

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

Error: The react render method is unable to determine the length of an undefined property

I created this component to extract the length of the followers array in order to display the number of followers each user has on their profile. The fetchUser() function is used to call a backend API, and I implemented Redux and Reselect for state managem ...

Utilizing Highcharts with AJAX/JSON integration and SQL Server in ASP.NET

As a newcomer to Highcharts and working with JSON data, I am encountering difficulties in creating a simple column chart. Below is the code I have been using: HTML: <div id="container"></div> Javascript: $(document).ready(function ...

Choose a file in React by specifying its path instead of manually picking a file

Is there a way for me to automatically select a file from a specified path into my state variable without having to open a select file dialog? I'm looking for a solution where I can bypass the manual selection process. Any suggestions on how this can ...

Can a background image flow into another div?

My goal is to use this specific image as the background image for this particular page. I want the background image to begin within the navbar navbar-default class. However, I'm facing an issue. I need the image to extend into the next div, which is d ...

Conceal CSS navigation bar with a single click

Is there a way to hide the dropdown menu after clicking on any item? How can I make it return to its initial state? Primarily, I want it hidden for mobile users. It currently works fine but remains open on mobile devices until another part of the page is c ...

Tips for overcoming indentation issues using ESLint?

Ever since I started using Vue 3 with ESlint, I've been encountering a new problem. Whenever I try to run my code, I am bombarded with numerous errors like: --fix option.</p> I'm looking for ways to disable this troublesome feature of ESl ...

Refining an array data table within a nested component

Transitioning my old PHP/jquery single-page applications to VueJS/Webpack has been a journey I'm undertaking to familiarize myself with the latter technology. It involves converting a simple table that pulls data from a JSON API and incorporates filte ...

Angular 2 component stays static despite changes in route parameters

So, I am in need of a way to refresh my component after the URL parameter's id has been altered. The following code is from my player.component.ts: import {Component, OnInit, AfterViewInit} from '@angular/core'; import {ActivatedRoute, Rout ...

Can you explain the significance of the ColSpan property in the Material UI TablePagination?

Why is ColSpan used in this code snippet? Reference: https://material-ui.com/components/tables/#table Check for the arrow symbol <TableFooter> <TableRow> <TablePagination rowsPerPageOptions={[5, ...

I'm looking to customize and expand the functionality of the IFormFile Interface in .NET Core. Specifically, I need to find a way to include additional data to the serialized array whenever an

I am in need of assistance with uploading a file using .net core. Currently, I am utilizing a multipart form and AJAX for this purpose. However, my requirement is slightly unique. I must be able to include additional data in the serialized array before b ...

Using Jquery to generate key value pairs from a form that is submitted dynamically

I'm still learning the ropes of jquery and struggling with a specific issue. I'm looking for a way to dynamically set key:value pairs in the code below based on form inputs that have variable values. The code works when I manually add the key:va ...

What is the best way to submit a form using Vue Axios in combination with Symfony 4

Need help! I am struggling with sending data from my Vue app to Symfony using axios. Even though I try to send the data, the Symfony request doesn't seem to receive it. Check out my controller code below: $form = $this->createForm(TeacherType::cl ...

AngularJS: Utilizing $http to fetch XML data instead of JSON

Looking to extract data from a website using angularjs / javascript. I am familiar with the $http object in angularjs which can make get requests. I have used it before to retrieve json, but I'm wondering if I can use it for XML (HTML) as well? (I th ...

Unable to successfully send multiple values from input fields using forms in PHP

I am currently facing an issue with my HTML form that contains a field consisting of multiple selection boxes as shown below: <div class="form-group"> <select multiple name="Fee[]"> ...

Error: Cannot locate module: Vue not found, incorrect path specified

I am facing an issue with my webpack configuration. I have placed my webpack.config.js and node_modules in a subfolder. When attempting to run the command npm run build, I encounter the following error: ERROR in ../public/Vue/Components/Rating.vue Module n ...

What enables typescript to be eligible for transpiling is its equivalent level of abstraction to javascript?

Transpilation is the act of converting code from one language to another with a similar level of abstraction. Can you point out some distinctive characteristics that indicate TypeScript transpires into JavaScript? ...

Avoid altering the state directly; utilize setState() to update it instead. Remember to follow react/no-direct-mutation

Here's the code snippet I'm working with: constructor(props) { super(props) this.state = { loginButton: '', benchmarkList: '' } if (props.username == null) { this.state.loginButton = &l ...

What steps can I take to display lines in a textarea so that it closely resembles the appearance of a notepad document

Is there a way to display lines in a text-area to give it the appearance of a notepad? I only have one text-area available. See the example notepad below for reference. ...

What is the process of encrypting a password using AngularJS on the client side, transferring it securely to the server through ExpressJS, and then decrypting it on the server

Looking for a simple method to encrypt a password on the client side using angular.js, send it to the server with express.js, and then decrypt it? While there are libraries like angular-bcrypt and similar ones in nodeJS, they may not be suitable as they ma ...

Calculating the position of a parallax background within a window

Seeking assistance with what initially seemed like a straightforward task, but has now become quite puzzling. I'm currently working on a basic jQuery script that binds to the window scroll function. Despite seemingly having all the necessary variable ...