Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

mesqueeb's avatar

Vue-Resource gives TokenMismatchException in Ajax call

Trying to post data with ajax. Even though I set my CSRF token right to my knowledge, I'm not sure why it won't work.

When checking the console, it seems I have 3 cookies: two Request cookies of which one is called XSRF-TOKEN and one is called laravel_session. And one respone laravel_session cookie. All have a different value!!!

My Vue:

new Vue({
    el:'body',
    http: {
        root: '/root',
        headers: {
            'X-CSRF-Token': $('meta[name=_token]').attr('content')
        }
    },  
});

My head:

<meta name="_token" content="{!! csrf_token() !!}"/>

My component:

addNew(){
    var thing = this.newThing;  // get input
    this.$http.post('/api/things/',thing)
}

My route:

Route::post('/api/things',function(){
    return App\Thing::create(Request::get());
});
0 likes
2 replies
mesqueeb's avatar
mesqueeb
OP
Best Answer
Level 5

I found the answer myself:

If you're gonna work with a vue-component, you should just add the token to that component instead. Otherwise it won't go with your ajax request. So put this part underneath the template in the component:

    http: {
        root: '/root',
        headers: {
            'X-CSRF-Token': $('meta[name=_token]').attr('content')
        }
    },  

Do this to check if your token was properly sent inside the headers:

  1. Go to google chrome, open dev-tools, go to the network tab and Reload.
  2. Make the ajax call and look at the file added in the network tab, open it and go to the 'Headers' tab.
  3. Look at the bottom where it says: 'Request Headers' and check if the token was properly added in the request.

Please or to participate in this conversation.