php - Laravel 8 route login not found with api 401 errors

one text

Solution:

This is happening because Laravel is probably throwing AuthenticationException exception. That logic is defined in the the default Illuminate/Foundation/Exceptions/Handler.php in the method unauthenticated():

protected function unauthenticated($request, AuthenticationException $exception)
{
    if ($request->expectsJson()) {
        return response()->json(['error' => 'Unauthenticated.'], 401);
    }

    return redirect()->guest(route('login'));
}

As you can see, in this default example, if your API excepts a JSON response, you would get JSON response with 401 HTTP code. If that's not the case, you would be redirected to the login (hence the error, because you don't have the login route defined)

So, in order to solve this, you can do two things.

The first one is to override this method and actually write your own condition and responses. You can do that by just defining unauthenticated() method in your custom Handler.php. You could do something like this:

protected function unauthenticated($request, AuthenticationException $exception)
{
    //This will return just a plain 401 page
    return response('Unauthenticated.', 401);
}

But, since this is probably an API, it would be better to use the second solution, which would be to just include Accept: application/json in your request header. This tells your API that you are sending a JSON request. In this case, you don't need to override the unauthenticated(), because this exception will be caught in the following condition, from the default Laravel handler:

if ($request->expectsJson()) {
   return response()->json(['error' => 'Unauthenticated.'], 401);
}

When this block of code is triggered, you will get a JSON response with 401 HTTP code, which is the expected one for the API's. If you need any more help, let me know.

Source