简体   繁体   中英

laravel shows old CSRF tokens resulting in a tokenmismatchException

I'm using Laravel for a project where I need the CSRF token for API calls. My CSRF meta tag sometimes contains tokens that are expired. By refreshing it's good to go for like 10 new calls. So after like 10 refreshes I get the TokenMismatchException from my AJAX calls. Making this API call an CSRF exception is not an option because the API call is heavy-loaded and contains valuable information.

I didn't customize any middelware classes.

My AJAX call in javascript looks like this:

$.ajax({
        url: '/getAllProducts',
        type: 'POST',
        data: {
            type: "gpu",
            hash: md5hash,
            _token: $('meta[name="csrf-token"]').attr('content')

        },
        dataType: 'json',
        success: function (response) {
            md5hash = '';
            products = response;
            $('.more-information').fadeIn();
            $.getScript("/js/filter-products.js", function(){
                filterProducts();
            });

            $.getScript("/js/createPopup.js", function(){
                $('.more-information').on('click', createPopup);
                $('.open-details').on('click', createPopup);
            });
        }
    });

My route looks like this

route::post('/getAllProducts', 'PartsController@getAllProducts');

The meta csrf token is generated like the standard Laravel app.blade.php

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

I'm aware there are other questions about this issue but I didn't find a solution. I tried several of them.

Here is the list of solutions I tried:

  • add jquery Ajaxsetup
  • update laravel
  • clear cache

Really hope someone can help me

Set token in ajax setup.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM