How to fix CSRF token not found on laravel 5.4, i try to learn vue js in laravel but i have error in my console "CSRF token not found", help me how to fix this error.
How to fix CSRF token not found on laravel 5.4, i try to learn vue js in laravel but i have error in my console "CSRF token not found", help me how to fix this error.
1) Where this error come from ?
This error come from resources/js/bootstrap.js
2) Why this error occured ?
see below snippet , it is try to find out meta tag of name csrf-token , if token found then add as headers to axios http library.else show error
let token = document.head.querySelector('meta[name="csrf-token"]');
if (token) {
window.axios.defaults.headers.common['X-CSRF-TOKEN'] = token.content;
} else {
console.error('CSRF token not found: https://laravel.com/docs/csrf#csrf-x-csrf-token');
}
3) What is the Solution ?
VerifyCsrfToken middleware will check for the X-CSRF-TOKEN request header.
You could store the token in an HTML meta tag:
<meta name="csrf-token" content="{{ csrf_token() }}">
It will generate token as shown in Image :
For Ajax Request :
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
For VueJS 2.0 :
Vue.http.headers.common['X-CSRF-TOKEN'] = document.head.querySelector('meta[name="csrf-token"]').content;
read more about CSRF token : https://laravel.com/docs/5.8/csrf
If you are using
let token = document.head.querySelector('meta[name="csrf-token"]');
Try using
let token = document.querySelector('meta[name="csrf-token"]');
Basically your script is unable to read meta tag with csrf-token, in that case, this should work.
What could be a problem as well is if you're ending a @section with a semicolumn. Like what happened with me I was doing
@endsection;
Which caused the error. When I changed it to
@endsection
The error was gone.
Or Else You can simply pass the URl in $except array, to exclude that URL from CSRF verification.
File
app/Http/Middleware/VerifyCsrfToken.php
Like this
protected $except = [
"readPDF/*",
];
This solution only applies when particular URL is need to be excluded from csrf verification so use it carefully guys.
In your bootstrap.js file replace this line document.head.querySelector('meta[name="csrf-token"]'); by $('meta[name="csrf-token"]').attr('content');
It would be
let token = $('meta[name="csrf-token"]').attr('content');
if (token) {
window.axios.defaults.headers.common['X-CSRF-TOKEN'] = token;
} else {
console.error('CSRF token not found: https://laravel.com/docs/csrf#csrf-x-
csrf-token');
}
This also solves the post-axios requests when you have forms in a vue component.