Laravel:在 ajax 请求会话过期后重定向到登录

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29072999/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 11:08:50  来源:igfitidea点击:

Laravel: Redirect to login after session has expired on ajax request

javascriptphpjqueryajaxlaravel

提问by haakym

If I log in to my web app, wait for the session to expire, then make an ajax request with a form in my web app I get the following error show up in the console:

如果我登录到我的 Web 应用程序,等待会话过期,然后在我的 Web 应用程序中使用表单发出 ajax 请求,我会在控制台中显示以下错误:

Failed to load resource: the server responded with a status of 500 (Internal Server Error)

Failed to load resource: the server responded with a status of 500 (Internal Server Error)

Ideally what would happen is a redirect to the login page or an error message shows up under the form that fired the ajax request (i.e. something meaningful to the user). It may be worth noting I already have the client side code to throw up errors to show an error message to the user if they make a validation error on the form.

理想情况下会发生什么是重定向到登录页面或错误消息显示在触发 ajax 请求的表单下(即对用户有意义的内容)。可能值得注意的是,如果用户在表单上发生验证错误,我已经有了客户端代码来抛出错误以向用户显示错误消息。

I believe I have an idea how to check if the session is expired and return something useful to the user telling them to login but I'm unsure how I'd implement this globally. So I'm wondering is it possible to handle this issue globally from the back end in Laravel and (or) do I need to write some logic for each ajax request to catch the issue to show an error message client side?

我相信我知道如何检查会话是否已过期并向用户返回一些有用的信息,告诉他们登录,但我不确定如何在全局范围内实现这一点。所以我想知道是否有可能从 Laravel 的后端全局处理这个问题和(或)我是否需要为每个 ajax 请求编写一些逻辑来捕获问题以显示错误消息客户端?

I'm using Laravel and Javascript/JQuery. Thanks for any help!

我正在使用 Laravel 和 Javascript/JQuery。谢谢你的帮助!

回答by Limon Monte

Here's the quick solution for your case:

这是针对您的情况的快速解决方案:

Controller(e.g. AuthController.php):

控制器(例如 AuthController.php):

/**
 * Check user session.
 *
 * @return Response
 */
public function checkSession()
{
    return Response::json(['guest' => Auth::guest()]);
}

Also, probably it will be needed to add this method name to ignore by guestmiddleware:

此外,可能需要添加此方法名称以被guest中间件忽略:

$this->middleware('guest', ['except' => ['logout', 'checkSession']]);

Route:

路线:

Route::get('check-session', 'Auth\AuthController@checkSession');

Layout(JS part), only for signed in users:

布局(JS部分),仅供登录用户使用:

@if (Auth::user())
  <script>
    $(function() {
      setInterval(function checkSession() {
        $.get('/check-session', function(data) {
          // if session was expired
          if (data.guest) {
            // redirect to login page
            // location.assign('/auth/login');

            // or, may be better, just reload page
            location.reload();
          }
        });
      }, 60000); // every minute
    });
  </script>
@endif

回答by itachi

use Middleware

使用中间件

Middleware:

中间件:

<?php namespace App\Http\Middleware;

class OldMiddleware {

    /**
     * Run the request filter.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
       if(!**condition to check login**)
       {
         // if session is expired
          return response()->json(['message' => 'Forbidden!'],403);
       }

        return $next($request);
    }

}

Route:

路线:

Route::group(['middleware' => '\App\Http\Middleware\OldMiddleware'], function(){
    //put the routes which needs authentication to complete
});

View:

看法:

$.ajax({

     type: 'post',
     url: {{route('someroute')}}
    //etc etc

}).done(function(data){
    //do if request succeeds
}).fail(function(x,y,z){
    //show error message or redirect since it is failed.
});