3

I want to check if user is logged in through JavaScript fetch() function. But it always returns false, but if I called the URL directly in address bar, it returns true as it is supposed to. Here is the code:

/routes/web.php

Route::get('check-login', function () {
    if (Auth::check()) {
       return response()->json(['isLogin'=>'ok']);
    } else  {
       return response()->json(['isLogin'=>'no']);
    }
});

javascript:

fetch('/check-login', {
            headers:{
                'Accept': 'application/json'
            }
        })
            .then(response => {
                return response.json();
            })
            .then(result => {
                console.log(result);
            });

What's wrong with my method?

Frumentius
  • 349
  • 2
  • 16

2 Answers2

2

Maybe it's because you aren't specifying that credentials should be included, Fetch Api don't use cookie by default. So maybe like this it will work:

fetch('/check-login', {
        headers:{
            'Accept': 'application/json'
        },
        credentials: 'same-origin'
    })
        .then(response => {
            return response.json();
        })
        .then(result => {
            console.log(result);
        });
Pol Lluis
  • 1,152
  • 7
  • 17
1

I dont know your javascript code right or wrong but routes\web.php must be

Route::get('check-login', function () {
    if (Auth::check()) {
        return response()->json(['isLogin'=>'ok']);
    } else {
        return response()->json(['isLogin'=>'no']);
    }
});

This code equivalent (more readability)

Route::get('check-login', function () {

   if (Auth::check()) {
       return response()->json(['isLogin'=>'ok']);
   }

   return response()->json(['isLogin'=>'no']);

});

Or you can use ternary operator

Route::get('check-login', function () {
   $isLogin = Auth::check() ? 'ok' : 'no';
   return response()->json(['isLogin'=> $isLogin]); 
});
Davit Zeynalyan
  • 8,418
  • 5
  • 30
  • 55
  • yup sorry for the typo, the return statement is exist in my code, i just forgot to type in when creating this thread. – Frumentius Jun 04 '18 at 10:29