Laravel and AJAX sporadic 401 errors in a poller

余生颓废 提交于 2019-12-05 11:19:44

After many hours of testing I believe I solved this issue even if I do not fully understand how and even if this is a universal answer that can be applied to similar cases.

Early in development I had the VerifyCsrfToken middleware disabled in kernel.php so I was not sending any _token with my AJAX requests. Enabling VerifyCsrfToken middleware and sending the _token immediately made all HTTP 401 errors disappear. Now, I started to get a different issue: even more sporadic HTTP 500 errors. A quick glance at the logs showed that all HTTP 500 errors were caused by TokenMismatchException.

I then came across this. Following the webpage instructions I put this in my master.page header:

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

And this in my master.page javascript:

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

And somehow everything is fine now. So, for all intents and purposes, my original problem is solved but I still cannot understand:

1 – Why was I getting sporadic HTTP 401 errors when I was not sending any _token with my AJAX requests if I had VerifyCsrfToken middleware disabled in kernel.php?

2 – Why did I started to get sporadic TokenMismatchException when I enabled VerifyCsrfToken middleware in kernel.php if I started to send the _token with my AJAX requests?

3 – Why did X-CSRF-TOKEN finally solved the HTTP 500 error issue? Bear in mind that all errors were sporadic and not permanent: I would risk saying that 95 to 98% of all AJAX requests went fine, only a small number of them had any issue whatsoever.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!