【问题标题】:Cakephp not routing to correct url, leaving url param emptyCakephp 没有路由到正确的 url,使 url 参数为空
【发布时间】:2012-02-13 21:53:36
【问题描述】:

我正在尝试为我的登录用户设置视图。我从 cakephp 2.0 手册中提取了代码。这是控制器代码:

public function view($id = null) {

    $this->User->id = $id;
    if (!$this->User->exists()) {
        throw new NotFoundException(__('Invalid user'));
    }

    $this->set('user', $this->User->read(null, $id));
}

当 user_id 为 1 的用户登录时,cake 不会转到 /users/1。相反,它只是转到 /users/view。以下是与用户控制器有关的路由:

Router::connect('/users', array('controller' => 'users', 'action' => 'login'));
Router::connect('/users/:action', array('controller' => 'users'));
Router::connect('/users/:id', array('controller' => 'users', 'action' => 'view'));

我不确定我错了,是路由代码还是控制器代码。

更新新的控制器功能:

public function view($id = null) {

    $this->User->id = $id;
    if (!$this->User->exists()) :
        throw new NotFoundException(__('Invalid user'));

    elseif($this->Auth->login()) :
return $this->redirect(array('controller' => 'users', 'action' => 'view', AuthComponent::user('id')));

    endif;
    $this->set('user', $this->User->read(null, $id));
}

【问题讨论】:

    标签: url-routing cakephp-2.0


    【解决方案1】:

    成功登录后 Cake 打开的页面要么是未经身份验证的用户最初尝试打开的页面,要么是 (App)Controller 中 Auth 组件的 loginRedirect 属性中设置的操作。还有documented here。换句话说,上面的代码与你描述/请求的行为无关。

    在这种情况下,由于 user_id 仅在成功登录后可用(因此无法在 loginRedirect 中设置),您需要在您的 UsersController 中调整登录操作,以使其成为类似的东西的:

    if ($this->Auth->login()) {
        return $this->redirect(array('controller' => 'users', 'action' => 'view', AuthComponent::user('id'));
    }
    

    【讨论】:

    • 我明白你在说什么,所以我拿出了关于抛出异常的代码并改用它。它以 /users/view/18 身份登录,chrome 给了我一个重定向循环错误。我是否应该将重定向命令直接返回到它所在的控制器操作?将为 OP 添加新功能。
    • 不,你误读了我的回答。这段代码应该在您的登录操作中,而不是在您的视图操作中。
    • 对不起,糟糕的时刻!好的,这成功登录,没有循环错误,但是它仍然路由到 /users/view/18。我不明白如何告诉蛋糕去 /users/18。我真的很感谢你的帮助;因为我实际上是一个编程菜鸟,所以你为我提供了几个啊哈,而 cakephp 手册只是让我不清楚。
    • @HeatherWalters 如果这是您希望它转到的 URL,只需将重定向位替换为该确切的 URL 语法,例如:return $this->redirect('/users/' . AuthComponent::user('id'));。确保您有可以处理此类请求的路由 a,但据我从您上面发布的路由中可以看出,这应该可以正常工作。
    猜你喜欢
    • 1970-01-01
    • 2015-11-20
    • 1970-01-01
    • 2015-10-02
    • 2011-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多