Laravel 5.3 Ajax Login

I am trying to login with my users using ajax with a new Laravel 5.3 project.

I created auth routes that were added to my web.php:

Auth::routes();

I have an html form with an email address as well as passwords and csrf field. Then I also have this javascript file:

$("form.login").submit(function(e) {
    e.preventDefault();

    $.ajax({   
        method: "POST",
        dataType: "json",
        headers: { 
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
        },
        data: $("form.login").serialize(),
        url: "/login"
    })
    .done(function(data) {
        console.log(data);
    });
});

When I submit it, this is displayed on my network tab: chrome dev tools

It redirects back to the original page without returning any data.

Why is he doing this? Does 5.3 give json answers more?

+4
source share
2 answers

Complete solution:

Hello, receivers,

5.3, , , :) .

-, App\Http\Controllers\Api Auth, auth api, , auth- (LoginController, ForgotPasswordController, RegisterController) .

LoginController: , .

: , .

: , .

: , 5 .

     /**
     * Send the response after the user was authenticated.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    protected function sendLoginResponse(Request $request) {
        $this->clearLoginAttempts($request);

        return response()->json(['SUCCESS' => 'AUTHENTICATED'], 200);
    }

    /**
     * Get the failed login response instance.
     *
     * @return \Illuminate\Http\Response
     */
    protected function sendFailedLoginResponse() {
        return response()->json(['ERROR' => 'AUTH_FAILED'], 401);
    }

    /**
     * Error after determining they are locked out.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    protected function sendLockoutResponse(Request $request) {
        $seconds = $this->limiter()->availableIn(
            $this->throttleKey($request)
        );

        return response()->json(['ERROR' => 'TOO_MANY_ATTEMPTS', 'WAIT' => $seconds], 401);
    }

RegisterController: , .

: , () .

: , .

    /**
     * Handle a registration request for the application.
     *
     * @param Request $request
     * @return \Illuminate\Http\Response
     */
    public function register(Request $request) {
        $validator = $this->validator($request->all());

        if($validator->fails())
            return response()->json(['ERROR' => $validator->errors()->getMessages()], 422);

        event(new Registered($user = $this->create($request->all())));

        $this->guard()->login($user);

        return $this->registered($request, $user)
            ?: redirect($this->redirectPath());
    }

    /**
     * The user has been registered.
     *
     * @param Request $request
     * @param  mixed $user
     * @return mixed
     */
    protected function registered(Request $request, $user) {
        return response()->json(['SUCCESS' => 'AUTHENTICATED']);
    }

ForgotPasswordController: , .

reset, json .

     /**
     * Send a reset link to the given user.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function sendResetLinkEmail(Request $request)
    {
        $validator = Validator::make($request->only('email'), [
            'email' => 'required|email',
        ]);

        if ($validator->fails())
            return response()->json(['ERROR' => 'VALID_EMAIL_REQUIRED'], 422);

        // We will send the password reset link to this user. Once we have attempted
        // to send the link, we will examine the response then see the message we
        // need to show to the user. Finally, we'll send out a proper response.
        $response = $this->broker()->sendResetLink(
            $request->only('email')
        );

        if ($response === Password::RESET_LINK_SENT) {
            return response()->json(['SUCCESS' => 'EMAIL_SENT'], 200);
        }

        // If an error was returned by the password broker, we will get this message
        // translated so we can notify a user of the problem. We'll redirect back
        // to where the users came from so they can attempt this process again.
        return response()->json(['ERROR' => 'EMAIL_NOT_FOUND'], 401);
    }
+4

( , op), . .

@iSensical

app/Exceptions/Handler.php unauthenticated, , json expectsJson().

Laravel . , , . .

ajax Laravel.

:

$http({
    url     : '{{ route('angular.auth.login.post') }}',
    method  : 'POST',
    data    : $.param($scope.user)+'&x-csrf-token='+CSRF_TOKEN,
    headers : { 'Content-Type': 'application/x-www-form-urlencoded' }
})
[...]

, bad Content-Type. application/json :

headers : { 'Content-Type': 'application/json' }
+1

Source: https://habr.com/ru/post/1655693/


All Articles