Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel and AJAX sporadic 401 errors in a poller

I’m coding an auction website in Laravel 5.0 that simulates realtime updates by using an AJAX poller that is executed every 5 seconds. The problem is that my server returns sporadic HTTP 401 status.

My route is build like this:

Route::post(auction/live/update, 'AuctionController@ajaxSendUpdate');

My controller is like this:

public function ajaxSendUpdate() {
    // Business logic: queries database, couple of Ifs, etc…
    $data = array('success' => true, 'otherStuff' => $myData);
    return Response::json($data);
}

Finally my poller is setup like this:

// a bit of HTML
function getAuctionUpdate() {
    setTimeout(function () {
    $.ajax({
        type: "POST",
        url: "{!! url('auction/live/update')!!}",
            dataType: 'json',
            data: {
                auctionID: $('#auctionID').val()
            },
            success: function (data) {
                if (data['success']) {
                    // Updates some labels, etc.
                   getAuctionUpdate(); // Rearms itself
                }
            }
    } }); // Not sure if all brackets are correct in this snippet but they are 100% on real code
}, 5000);

This code runs fine about 95% of times. However it can break with 2 different outcomes:

1) Server responds error 401 after some time and never recovers. In this scenario we need to login again. After login, everything goes well and this outcome never occurs again.

2) Server responds with sporadic 401 but recovers in the next (or after a few) polling requests.

I’m using Laravel 5.0 and an up-to-date version of Xampp on Windows. The error is easily reproduced with WAMP on Windows. Not tested in Linux nor OSX. I've read this and this and assorted threads in laracasts.com and other forums but I am unable to solve the problem...

like image 628
Ricardo Isec Avatar asked Nov 10 '22 02:11

Ricardo Isec


1 Answers

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.

like image 163
Ricardo Isec Avatar answered Nov 14 '22 21:11

Ricardo Isec