Axios not sending XSRF token with headers

  axios, csrf, laravel, laravel-sanctum, vue.js

I am integrating a Vue JS (Quasar framework) based SPA with API. The API is built in Laravel and is using sanctum for CSRF.

When I send a request to the sanctum endpoint https://someweburl.com/sanctum/csrf-cookie it sends the XSRF-TOKEN as cookie correctly. But when I am sending the the POST request, the X-XSRF-TOKEN is not attaching itself with the header. And I am getting a ‘token mismatch’ error.

The front-end is on my localhost:8080 while the API is live on a url. I do not have direct access to the Laravel project but only the API.

Following is my axios configuration

import Vue from 'vue';
import axios from 'axios';

Vue.prototype.$axios = axios;

const apiBaseUrl = "https://someweburl.com";
const api = axios.create({ baseURL: apiBaseUrl });

api.defaults.withCredentials = true;

Vue.prototype.$api = api;
Vue.prototype.$apiBaseURL = apiBaseUrl;


export { axios, api, apiBaseUrl }

Following is the request format that I am trying to achieve i.e A POST request after getting the CSRF

export const fetchAllEvents = async function (context, payload) {
    this._vm.$api.get('/sanctum/csrf-cookie').then(response => {
        this._vm.$api.post('/api/website/event/all').then(response => {
            context.commit('setAllEvents', response.data.data);
        }).catch(error => {
            console.log(error);
        })
    }).catch(error => {
        console.log(error);
    })
}

Any help will be appreciated.

Source: Laravel

Leave a Reply