首页 文章

Laravel 5.3 Ajax 登录

提问于
浏览
4

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

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

Auth::routes();

我有一个带有电子邮件,密码输入和 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);
    });
});

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

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

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

2 回答

  • 5

    完整解决方案:

    嗨 reinierkors,

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

    首先,我在AppHttpControllersApi下创建了一个名为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);
        }
    

    **在 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 类中:**我重写了正在进行重定向的函数。

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

    有关我的错误(与 op 相同的类型)的解释,请参阅编辑这篇文章的历史

    我是怎么解决

    @iSensical得到一点帮助

    app/Exceptions/Handler.php内部有一个unauthenticated函数,默认情况下,它知道请求是否需要expectsJson()函数的json答案。

    问题并非来自 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' }
    })
    [...]
    

    我们可能使用了坏Content-Type。正确的是application/json像这样:

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

相关问题