Laravel 5.2 | CSRF Token mismatch

2019-09-12 11:10发布

问题:

I'm using AJAX post request and sending with CSRF-TOKEN - on my local server worked well, but on my IIS SERV TokenMismatchException in VerifyCsrfToken.php line 67:

This is the code:

               $.ajax({
                    url     : '{{ route('dashboard.ajax.update') }}',
                    method  : 'POST',
                    data    : {
                        table       : 'categories',
                        data        : {
                            order: $count
                        },
                        conditions  : {
                            id: $id
                        }
                    },
                    dataType: 'JSON',
                    headers : {
                        "X-CSRF-TOKEN": '{{ csrf_token() }}'
                    }
                });

In the console I can see the request with: X-CSRF-TOKEN:w3liodqf8bdOvWH9uVTzLHVVsE0L1uIlCpnOyVVS

What can cause this problem?

回答1:

    $.ajax({
        type: 'POST',
        url: 'stringUrl',
        beforeSend: function (xhr) {
            xhr.setRequestHeader('X-CSRF-TOKEN', '{{ csrf_token() }}');
        },
        data: {
            'id': $id // etc..
        },
        cache: false,
        error: function (xhr, type, exception) {
            console.log("ajax error response type " + type);
        }
    });

Try to set it on "beforeSend" event



回答2:

The problem was in my sessions. I've cleaned all my sessions files, cleaned the cache and used php artisan key:generate. After this - work pretty ok.