0

one of my application page is loading some content via ajax in my page (currently 2 requests, after document ready). Many times I receive for this ajax requests the status "401" with response "Unauthorized.". Sometimes on refresh the page (with F5) is it working, Some times ony one request is receiving 401 status. And less times i receive 500 (laravel is in this case using wrong database credentials, not from .env).

Can anyone help me with this issues?

Using Laravel 5.1.6

Thanks

public function handle($request, Closure $next)
{
    if ($this->auth->guest()) {
        if ($request->ajax()) {
            return response('Unauthorized.', 401);
        } else {
            return redirect()->guest('auth/login');
        }
    }

    return $next($request);
}
AliNasiri
  • 137
  • 1
  • 3
  • 11
  • Are you authorised? What happens if you visit routes that use the same middleware in the browser? – Jeemusu Sep 07 '15 at 07:26
  • ome times ony one request is receiving 401 status. For example after 5 ajax request It happens.I am logon and test this line code (dd($this->auth->guest())), The print "true", If after logon value should be "false" – AliNasiri Sep 07 '15 at 07:45
  • But this only happens when using AJAX? The same authenticated routes work fine when viewed in a browser? – Jeemusu Sep 07 '15 at 07:46
  • Your middleware will send 401 response if the user **not logged in** and using **ajax**. How should it work? – Iamzozo Sep 07 '15 at 09:09
  • after the 5 request ajax for datatable happens this Error – AliNasiri Sep 08 '15 at 07:45

2 Answers2

0

You can try using ' || $request->wantsJson() ' with the if for checking if the request is ajax.

if ($request->ajax() || $request->wantsJson()) {
        return response('Unauthorized.', 401);
    } else {
        return redirect()->guest('auth/login');
    }
Basit
  • 936
  • 5
  • 13
0

This is due to your login session. Whenever your session expire. Request Response is "Unauthorized".

M Arfan
  • 4,384
  • 4
  • 29
  • 46