dericcain dericcain - 1 month ago 51
Ajax Question

Another Laravel Token Mismatch Exception issue

I have an application which uses AJAX quite a bit on a Laravel 5.3 application. I have some pages that are behind authentication and some that are not. The ones that are inside of authentication are working fine. The one that is outside (public facing) are giving me a the infamous

TokenMismatchException in VerifyCsrfToken.php line 68
. In order to attach the token to the AJAX header, I am using this...

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


And it is working because when I make a request, I can see this...
enter image description here

...but the tokens are not matching. When I go to the framework file
Illuminate\Foundation\Http\Middleware\VerifyCsrfToken::class
and do a
dd()
on the session token and the token that was passed, they do not match.

Things I have tried:


  1. Clearing Cache (views, config, cache)

  2. Changing session driver from
    file to Redis

  3. Using
    csrf_field()
    instead of AJAX headers



I cannot figure out why this is not working. Any other ideas?

Answer

And, I finally figured it out. I am using BrowserSync for livereload, which proxies all my requests to localhost:3000/*. When I was testing the public side, I was visiting it through the original domain name and not proxied through browsersync's localhost:3000 so that was causing session issues.

Basically, if you have BrowserSync running and you try in use your site not through browsersync, you can get token mismatch errors.