how to fix CSRF token not found on console

If you are using Vue, here's the way to go:

Vue.http.interceptors.push(function (request, next) {
request.headers['X-CSRF-TOKEN'] = Laravel.csrfToken;
next();
});

or

<script>
window.Laravel = <?php echo json_encode([
    'csrfToken' => csrf_token(),
]); ?>
</script>

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 :

enter image description here

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


You can add the following meta tag

<meta name="csrf-token" content="{{ csrf_token() }}">

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.

Tags:

Laravel