Search code examples
perlmojolicious

Controller not found in Mojolicious


I have some strange result in routing.

Reference code in PDNController.pm

    my $r = $self->routes;

    my $auth = $r->under('/' => sub {
    my $self = shift ;
    $self->redirect_to('/login') and return undef unless ($self->is_user_authenticated);
    return 1;
    });

    $r->get('/login')->to('login#index');

    $r->post('/login')->to('login#auth');

    $r->get('/logout')->to('login#logout');

    $auth->get('/')->to('index#index');

    $auth->get('/vlan')->to('vlan#index');

    $auth->get('/api/vlan/add')->to('vlan#add');

Reference code in PDNController/Controller/VLAN.pm

package PDNController::Controller::VLAN;
use Mojo::Base 'Mojolicious::Controller';

sub index {
  my $self = shift;
  $self->render();
}

sub add {
    my $self = shift;
    my %h;
    $h{error} = '';
    $self->res->headers->add( 'Access-Control-Allow-Origin' => '*' );
    $self->render(json => {%h}});  
}


1;

All routes from this example except /api/vlan/add work fine but with last i have an error

[Tue Mar  1 16:54:02 2016] [debug] GET "/api/vlan/add"
[Tue Mar  1 16:54:02 2016] [debug] Routing to a callback
[Tue Mar  1 16:54:02 2016] [debug] Controller "PDNController::Vlan" does not exist
[Tue Mar  1 16:54:02 2016] [debug] Template "vlan/add.html.ep" not found
[Tue Mar  1 16:54:02 2016] [debug] Template "not_found.development.html.ep" not found
[Tue Mar  1 16:54:02 2016] [debug] Template "not_found.html.ep" not found
[Tue Mar  1 16:54:02 2016] [debug] Rendering template "mojo/debug.html.ep"
[Tue Mar  1 16:54:02 2016] [debug] Rendering template "mojo/menubar.html.ep"
[Tue Mar  1 16:54:02 2016] [debug] 404 Not Found (0.052532s, 19.036/s)

Why controller name PDNController::Vlan and not PDNController::Controller::Vlan ?

Mojolicious 6.51


Solution

  • Your controller name is PDNController::Controller::VLAN,but your route says:

    $auth->get('/vlan')->to('vlan#index');
    

    That means you are searching for controller PDNController::Controller::Vlan(The controller-names are changed into initcap by Mojolicious ) which obviously does not exist.

    There is two solutions for this:

    1. Change your controller name PDNController::Controller::VLAN to PDNController::Controller::Vlan and the file inside Controller directory to Vlan.pm.
    2. OR Change the route to below.

      $auth->get('/vlan')->to('VLAN#index');

    Why controller name PDNController::Vlan and not PDNController::Controller::Vlan

    PDNController::Vlan in the error message points to controller PDNController::Controller::Vlan. The error message is designed to give you more clarity.

    When it is saying Controller "PDNController::Vlan" that means it is controller Vlan of PDNController app(all controllers of your app resides in Controller directory) i.e it is saying about PDNController::Controller::Vlan.