当模板请求返回 401 重定向时,如何使用 Laravel 将用户重定向到登录页面

How to redirect user to login page with Laravel when template request returns 401 redirect

本文关键字:重定向 Laravel 用户 登录 何使用 请求 返回      更新时间:2023-09-26

我有一个angularjs/laravelWeb应用程序,其中模板包含是动态加载的。

问题是,当用户的会话超时并且他们导航到页面上的新部分时,它将在服务器端进行重定向,并实际提供模板应该所在的登录页面。

如何拦截此模板请求,而是将用户重定向到登录页面,而不是简单地将登录页面作为模板返回?

在一个项目中,我们使用了这种拦截http错误的方式。在那里,您可以重定向到登录页面(或任何您喜欢的内容)。

function httpInterceptor($provide, $httpProvider) {
    function interceptorFunction($q) {
        return {
            responseError: function (rejection) {
                if (typeof rejection.status !== 'undefined') {
                    if (rejection.status === 401) {
                        //Your app will handle 401 errors here... 
                    } 
                }
                return $q.reject(rejection);
            }
        };
    }
    $provide.factory('httpInterceptor', interceptorFunction);
    interceptorFunction.$injector = ['$q'];
    $httpProvider.interceptors.push('httpInterceptor');
 angular.module('app', dependencies)
    .config(httpInterceptor);
"应用程序"模块

是我们的"主"模块。401错误应该发生,因此服务器应至少使用该状态代码进行一次响应。