laravelrequest

Laravel 10 - CSRF API request


I have this js code on the updated Laravel 5.7 -> Laravel 10. On the old version, this worked perfectly fine, however, here as soon as this js is started, when it is called, it gets damaged and stolen, or what to call it, the CSRF token, when it is no longer possible to use, for example token for logging in or to any form. I don't know how to solve this at all.

function pollActiveEvent() { var locale = localStorage.getItem('selectedLanguage') || 'default_locale';
    $.ajax({
        url: '/get-active-event-translations',
        type: 'GET',
        data: { locale: locale, _token: '{{ csrf_token() }}' },
        success: function(response) {
            updateActiveEvent(response);
            setTimeout(pollActiveEvent, 5000);
        },
        error: function() {
            console.error("Nepodařilo se provést požadavek na aktivní event.");
            setTimeout(pollActiveEvent, 5000);
        }
    });
}

pollActiveEvent();`

Solution

  • Have you ever thought about adding meta tag to blade element?

    <meta name="csrf-token" content="{{ csrf_token() }}">
    
    function pollActiveEvent() {
        var locale = localStorage.getItem('selectedLanguage') || 'default_locale';
        var csrfToken = $('meta[name="csrf-token"]').attr('content');
    
        $.ajax({
            url: '/get-active-event-translations',
            type: 'GET',
            headers: { 'X-CSRF-TOKEN': csrfToken },
            data: { locale: locale },
            success: function(response) {
                updateActiveEvent(response);
                setTimeout(pollActiveEvent, 5000);
            },
            error: function() {
                console.error("Failed to request active event.");
                setTimeout(pollActiveEvent, 5000);
            }
        });
    }
    
    pollActiveEvent();