Beu*_*biu 0 laravel vue.js axios laravel-7
我有一个管理区域和一个供普通用户使用。现在,当我的会话到期时,我会从管理区域重定向到主页,我必须刷新页面才能将我重定向到/login. 附注。我使用 Vue.js 作为前端。
我想在会话过期时重定向到我的 /login 页面,而不是主页,那时主页应该是不可见的。
网页.php
// Admin routes
Route::middleware(['can:admin'])->group(function () {
// all routes for admin, and when my session expire I get redirected from here
}
Route::middleware('guest')->get('/', function () {
return redirect('/login');
});
// Normal user routes
Route::middleware('auth')->get('/', function () {
return view('layouts.app');
});
Route::middleware('auth')->get('/{any}', function () {
return view('layouts.app');
})->where('any', '.*');
Run Code Online (Sandbox Code Playgroud)
身份验证服务提供者
public function boot()
{
$this->registerPolicies();
Gate::define('admin', function ($user) {
return !empty($user->roles()->where('admin_area', true)->first());
});
Gate::define('normal', function ($user) {
return !empty($user);
});
}
Run Code Online (Sandbox Code Playgroud)
一种解决方案是捕获403错误axios并进行硬刷新。但我知道这不太好。
在您的情况下,您提出的解决方案对我来说听起来不错。如果您无论如何都在执行 AJAX 请求,为什么不对 403 Unauthorized Response 做出反应并将用户重定向到您的登录页面!
实现这一点的一种方法是使用拦截器,如果您使用的是 axios。
这是他们文档中的简短代码片段:
// Add a response interceptor
axios.interceptors.response.use(function (response) {
// Any status code that lie within the range of 2xx cause this function to trigger
// Do something with response data
return response;
}, function (error) {
// Any status codes that falls outside the range of 2xx cause this function to trigger
// Do something with response error
if(error.response.status === 403) {
// redirect to login page
window.location.href = "/login";
}
return Promise.reject(error);
});
Run Code Online (Sandbox Code Playgroud)
对于其他人:
我认为您正在寻找的文件可能是 app/Http/Middleware/Authenticate.php
在这里,您将找到以下代码行:
/**
* Get the path the user should be redirected to when they are not authenticated.
*
* @param \Illuminate\Http\Request $request
* @return string|null
*/
protected function redirectTo($request)
{
if (! $request->expectsJson()) {
return route('login');
}
}
Run Code Online (Sandbox Code Playgroud)
如您所见,非 json 请求应重定向到名为login. 因此,请确保您的登录页面的路由也被命名login或相应地更改 Authenticate.php。
| 归档时间: |
|
| 查看次数: |
3154 次 |
| 最近记录: |