Laravel 5.3 Ajax登录

rei*_*ors 4 ajax jquery laravel-5 laravel-5.3

我正在尝试使用带有新Laravel 5.3项目的ajax登录我的用户.

我已经生成了auth路由,它已添加到我的web.php中:

Auth::routes();
Run Code Online (Sandbox Code Playgroud)

我有一个带有电子邮件,密码输入和csrf字段的html表单.然后我也有这个javascript文件:

$("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);
    });
});
Run Code Online (Sandbox Code Playgroud)

然而,当我发布它时,它显示在我的网络选项卡中: chrome dev工具

它会重定向回原始页面,而不会返回任何数据.

它为什么这样做?5.3不再给json回复吗?

Yoh*_*hel 5

完整解决方案:

嗨reinierkors,

我也尝试用5.3版本做同样的事情,我终于解决了它:)并且解决方案非常干净.

首先,我在App\Http\Controllers\Api创建了一个名为Auth 的新文件夹,我只是为了为api添加新的auth控制器,所以我可以重写一些函数,然后我复制了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);
    }
Run Code Online (Sandbox Code Playgroud)

在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']);
    }
Run Code Online (Sandbox Code Playgroud)

在ForgotPasswordController类中: 我重写了正在进行重定向的函数.

我修改了重置链接电子邮件功能,以便我们可以获取消息并显示为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);
    }
Run Code Online (Sandbox Code Playgroud)