I have been getting this error for the last week on all my axios POST/PUT/DELETE requests (GET requests work properly) to my api routes, eventhough I'm not using sanctum or any middleware to protect these routes.
I added the proper meta-tag to all my blade files:
<meta name="csrf-token" content="{{ csrf_token() }}">
I'm attaching csrf token to all my axios requests and setting withCredentials to true, inside bootstrap.js file.
window.axios = require('axios');
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
window.axios.defaults.headers.common['Content-Type'] = 'application/json';
window.axios.defaults.withCredentials = true;
window.axios.defaults.withXSRFToken = true;
/**
* Next we will register the CSRF Token as a common header with Axios so that
* all outgoing HTTP requests automatically have it attached. This is just
* a simple convenience so we don't have to attach every token manually.
*/
let token = document.head.querySelector('meta[name="csrf-token"]');
console.log(token);
if (token) {
window.axios.defaults.headers.common['X-CSRF-TOKEN'] = token.content;
console.log('CSRF token found');
} else {
console.error('CSRF token not found: https://laravel.com/docs/csrf#csrf-x-csrf-token');
}
My api route file (notice no middleware):
Route::post('/chats/test-endpoint','App\Http\Controllers\Api\ChatController@testEndpoint');
Api middlewares:
'api' => [
'throttle:api',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
EnsureFrontendRequestsAreStateful::class,
'throttle:60,1',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
I'm also inspecting the headers of the response and requests I'm getting from laravel with firefox devtools, and I noticed something:
In the request headers, Cookie XSRF-TOKEN ends in 0%3D and X-XSRF-TOKEN value ends with = instead, but they are almost identical except for that...
https://i.imgur.com/cptNjYa.png
In the response headers app session setCookie also ends in 0%3D
https://i.imgur.com/OrIidOA.png
Thank you in advance