TokenMismatchException after any ajax error in Laravel 5.1

2

I'm working with Laravel a short time and I'm having a problem when I use ajax requests. When my application returns any error and I try to send one more request, Laravel sends me this error:

TokenMismatchException in VerifyCsrfToken.php line 53:

If I update the page (with the error of my corrected code), it no longer sends this message. It may be any server-side error like variable missing, spelling, files, anything, that in the next independent request of the route I take it will return the above error.

Does anyone know how to solve this?

    
asked by anonymous 07.01.2016 / 11:57

2 answers

2

I think you can solve this as follows:

  • Display the token on some attribute of a DOM element
  • Capture this value of the DOM token in each ajax request and send it as the _token value.

Then, it could be done something like this:

<body data-token="{{ csrf_token() }}"></body>

In ajax:

$.ajax({
    data: {..., _token: $('body').data('token') }
});

Another way to configure your ajax requests (and I believe that is the most viable) is to use the $.ajaxSetup function, so that all requests inherit the header with the token. So:

$.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('body').data('token')
        }
  });

In the VerifyCsrfToken.php file, you will need to add this method:

protected function tokensMatch($request)
{

    if ($request->ajax()) {

       $token = $request->input('_token');

    } else {

       $token = $request->header('X-CSRF-Token');

    }

    return $request->session()->token() == $token;
}

Disabling Token

If you want to disable token checking on ajax requests (which I do not consider to be unsafe), you can do the following:

protected function tokensMatch($request)
{

    if ($request->ajax()) return true;        

    return $request->session()->token() == $token;
}
    
07.01.2016 / 12:02
3

Just complementing the response from @Wallace Maxters.

If there is no need to use CSRF protection anywhere in the project, you can disable this option completely by changing the app/Http/Kernel.php file and removing the \App\Http\Middleware\VerifyCsrfToken middleware

Remembering that by doing this you will no longer be protected against CSRF, if it is necessary to keep @Wallace Maxters' answer it is the right one.

More information:

link

    
07.01.2016 / 12:40