Question: Missing X-CSRF-TOKEN in Vue headers

Question

Missing X-CSRF-TOKEN in Vue headers

Answers 2
Added at 2016-12-29 20:12
Tags
Question

I'm trying to make a POST using VueJS 1.0.28 but I'm getting a Laravel 5.3 TokenMismatchException error.

This is in app.js to cover both jQuery and Vue:

Vue.http.interceptors.push((request, next) => {
    request.headers.set('X-CSRF-TOKEN', Laravel.csrfToken);

    next();
});

$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});

This is in the main.blade.php layout where we instantiate the Laravel value:

<script src="{!! asset('/js/app.js') !!}"></script>
<script>
    (function () {
        window.Laravel = {
            csrfToken: '{{ csrf_token() }}'
        };
    })();
</script>

When I look at the headers in the POST request, I don't see the X-CSRF included for Vue.

This is super basic stuff for jQuery and I'm a stumped what I misconfigured on the Vue side. Ideas?

Answers
nr: #1 dodano: 2016-12-29 21:12
  1. Move to Vue 2.* if possible.
  2. Don't mix Vue and jQuery. I promise, it will make your life easier.
  3. For handling AJAX use e.g. AXIOS
  4. If so, you will have just to use: axiosDefaults.headers.common['X-CSRF-Token'] = csrfToken;
nr: #2 dodano: 2016-12-30 00:12

As it turns out, both Vue and jQuery were getting the token, but the package code I was using was directly using XMLHttpRequest so it needed to get the token manually by doing:

xhr.setRequestHeader('X-CSRF-TOKEN', Laravel.csrfToken);
Source Show
◀ Wstecz