Laravel controller returning index view instead of json response

  apache2, jquery, laravel

I am using apache2 and php artisan serve command to test my project.

Have the next controller:

<?php
// file: HttpControllersAuthCtrl.php
namespace AppHttpControllers;

use IlluminateHttpRequest;
use AppUser; //  <--
use IlluminateSupportFacadesAuth;

class AuthCtrl extends Controller
{
    public function login(Request $request)
    {
        $rules = [ 'email' => 'required|exists:users',
                   'password'  => 'required' ];

        $request->validate($rules);

        $data = [ 'email' => $request->get('email'),
                  'password'  =>  $request->get('password') ];

        if( Auth::attempt($data) )
        {
            $user = Auth::user();
            // the $user->createToken('appName')->accessToken generates the JWT token that we can use
            return response()->json([
                                      'user'  =>  $user, // <- we're sending the user info for frontend usage
                                      'token' =>  $user->createToken('teltask')->accessToken, // <- token is generated and sent back to the front end
                                      'success' => true
                                    ]);
        }
        else
        {
            return response()->json([
                                    'success' => false,
                                    'msg' => 'Credenciales erroneas.'
                                    ]);
        }

    }
}

And a simple mock index.php that does an ajax call with the following js:

function ExecLogin()
{
    $.ajax({
        method: "POST",
        url: "http://127.0.0.1:8000/api/login",
        data : {email : "[email protected]", password: "mypass"}
    }).done(
    function(data, status) 
    {
        if(data.success == true)
        {
            localStorage.setItem('appname_token', data.token);
            // the following part makes sure that all the requests made later with jqXHR will automatically have this header.
            $( document ).ajaxSend(function( event, jqxhr, settings ) {
                jqxhr.setRequestHeader('Authorization', "Bearer " + data.token); 
            });
        }
        else
        {
            alert(data.msg);
        }
    }).fail(function(error){
        // handle the error
    });
} 

As you can see, when the code enters this part, (when the user authenticated OK), It returns a JSON response allright:

$user = Auth::user();
            // the $user->createToken('appName')->accessToken generates the JWT token that we can use
            return response()->json([
                                      'user'  =>  $user, // <- we're sending the user info for frontend usage
                                      'token' =>  $user->createToken('teltask')->accessToken, // <- token is generated and sent back to the front end
                                      'success' => true
                                    ]);

But when it did not authenticated OK, it enters at this part, but the response is the index.php text/html, not a json response as I defined:

return response()->json([
                          'success' => false,
                          'msg' => 'Credenciales erroneas.'
                                    ]);

Am I missing something important here?

Source: Laravel

Leave a Reply