thinkPHP6中在中间件中使用redirect不起作用
在tp6中写了个登录中间件如下 :
public function handle($request, \Closure $next) { if (!Session::has('user')) { return redirect('/admin/login'); } return $next($request); }
在登录过期后,刷新页面,在浏览器控制台也可以重定向到登录路由并返回登录视图,但是在页面上出来的还是之前访问的页面,并不是登录页面,求指教下这个是什么原因?
use \traits\controller\Jump; $this->redirect("/amaze/login?from=index"); 这样用,注意上面是个trait。
你尝试一下,当你定义完中间件,在
BaseController.php
控制器$middleware
属性中定义不要在全局中间件return,会造成重定向次数过多。 另外你的
login
控制器不要继承BaseController.php
他自己又好了,可以用了 :sob:
@xiaosheng 为何防止这种情况 进行 (string) redirect (), 你可以进行过 halt(热direct(‘’)), 实际返回的是一个对象,而我们需要的是 其中的 url
我再次出现了上面这个问题,这次是权限中间件,在thinkPHP6中,如果把中间件定义在路由中的话,在重定向的时候就很容易出现上面的情况,如果在控制器中定义的话就没有问题
最好给需要用的路由加个分组 ->middleware () 去使用这个中间件 :joy:
我这里用的没问题
public function handle($request, \Closure $next)
{
if (!Session::has('user')) {
return $this->redirect('/admin/login',302);
}
return $next($request);
}
public function redirect(...$args){
throw new HttpResponseException(redirect(...$args));
}
注:redirect跳转只有在action里生效.