CakePHP 3:缺少存在路由的路由错误

CakePHP 3: Missing route error for route that exists

CakePHP 3.0

我收到一个存在路由的 "Missing Route" 错误。

这是我的路线:

#my admin routes...
Router::prefix('admin', function($routes) {
    $routes->connect('/', ['controller'=>'Screens', 'action'=>'index']);
    $routes->connect('/screens', ['controller'=>'Screens', 'action'=>'index']);
    $routes->connect('/screens/index', ['controller'=>'Screens', 'action'=>'index']);
    //$routes->fallbacks('InflectedRoute');
});

Router::scope('/', function ($routes) {

    $routes->connect('/login', ['controller' => 'Pages', 'action' => 'display', 'login']);    
    $routes->connect('/pages/*', ['controller' => 'Pages', 'action' => 'display']);

    $routes->fallbacks('InflectedRoute');
});

Plugin::routes();

基本上我只是将顶部部分(用于管理路由)添加到开箱即用的默认路由中。

当我访问 /admin/screens/index 时,我看到以下错误:

注意错误消息:

Error: A route matching "array ( 'action' => 'add', 'prefix' => 'admin', 'plugin' => NULL, 'controller' => 'Screens', '_ext' => NULL, )" could not be found.

...这很奇怪,因为我没有尝试访问 add 操作。下面打印的参数看起来正确。

这是怎么回事?

仔细查看堆栈跟踪,错误并没有发生在调度过程中,你似乎认为,它是在你的视图模板中触发的,你可能正在尝试创建一个 link 到 add 操作,反向路由找不到匹配的路由,因此出现错误。

解决方案应该很明显,连接必要的路由,像

这样的显式路由
$routes->connect('/screens/add', ['controller' => 'Screens', 'action' => 'add']);

包罗万象

$routes->connect('/screens/:action', ['controller' => 'Screens']);

或者只是捕捉一切的后备

$routes->fallbacks('InflectedRoute');

如果使用前缀 admin,这对我有用:-

Router::prefix('admin', function ($routes) {
    // Because you are in the admin scope,
    // you do not need to include the /admin prefix
    // or the admin route element.
    $routes->connect('/', ['controller' => 'Users', 'action' => 'index']);
    $routes->extensions(['json', 'xml']);
    // All routes here will be prefixed with `/admin`
    $routes->connect('/admin', ['controller' => 'Order', 'action' => 'index']);
    // And have the prefix => admin route element added.
    $routes->fallbacks(DashedRoute::class);
});