在做角色权限或者登录的时候我们需要判断是否登录,这时我们可能会用到重定向跳转,但是你会发现TP6下构造方法下是无法重定向的,这是为何呢?
1、原因
这不是ThinkPHP6的BUG,这个问题不是BUG的原因是什么?原因是redirect()返回的是\think\response\Redirect对象,而此对象被app\BaseController类中的构造方法所获取。
vendor/topthink/framework/src/helper.php
if (!function_exists('redirect')) {
    /**
     * 获取\think\response\Redirect对象实例
     * @param string $url  重定向地址
     * @param int    $code 状态码
     * @return \think\response\Redirect
     */
    function redirect(string $url = '', int $code = 302): Redirect
    {
        return Response::create($url, 'redirect', $code);
    }
}2、解决无法使用redirect()重定向问题,我们可以重写重定向方法,在Base控制器下加入以下方法
    /**
     * 自定义重定向方法
     * @param $args
     */
    public function redirectTo(...$args)
    {
        // 此处 throw new HttpResponseException 抛出异常重定向
        throw new HttpResponseException(redirect(...$args));
    }3、使用方法
return $this->redirectTo((string)url('admin/Login/index'));综上,这样就能解决了ThinkPHP6无法重定向跳转问题
 
                     
                     
                                 
                                 
                         
                         
                         
                         
                         
                         
                         
                         
                
                 
                         
                         
                         
                         
                 关于简忆
关于简忆 简忆诞生的故事
简忆诞生的故事 
            


 粤ICP备16092285号
粤ICP备16092285号
文章评论(3)
lijulun2024-08-11 20:39:35
$response = Response::create($url, 'redirect'); $response->code($code)->with($with); throw new ******); 错误信息如下:rewrite or internal redirection cycle while processing "/index.php//index.php//index.php//index.php//index.php//index.php//index.php//index.php//index.php//index.php//index.php//shop/index/index.html", client: 172.17.0.1, server: , request: "GET /shop/index/index.html ******" 一直没懂这个错。回复