Mojolicious routes and templates

360 Views Asked by At

I am trying to make my first app with mojolicious and I have some routing issue. I have an angular app and I just would like to implement it and makeit work on my web werver. So I have a "app/index.html" file but I don't know how to make my webserver point on it when I am like on this adress "/appAngular".

I haven't find anythingabout it even if it seems to be basic, so if you can help i will be grateful.

2

There are 2 best solutions below

1
On

If you've started the web server correctly using defaults, your browser would point to x.x.x.x:3000 using the ip of the webserver. Mojolicious comes with a landing page and you can add .html files under public that will be served also. So if your angular app is already built out, that whole structure will need to go under public and you will need to delete the default template served under a new mojolicious app, should look something like this:

get '/' => sub {
  my $c = shift;
  $c->render(template => 'index');
};

The commands to start over:

mojo generate lite_app myapp
mkdir public
<copy your angular app into new directory public>
<delete default route>
morbo myapp
0
On

You will have to point your index.html page as the static page in Mojolicious. For example in full app:

In App:

package MojoNg4;
use Mojo::Base 'Mojolicious';
use Mojo::SQLite;

# This method will run once at server start
sub startup {
  my $self = shift;

  # Load configuration from hash returned by "my_app.conf"
  my $config = $self->plugin('Config');
  $self->plugin('PODRenderer') if $config->{perldoc};

  if (my $secrets = $self->config->{secrets}) {
      $self->secrets($secrets);
  }


  $self->hook(
      before_dispatch => sub {
          my $c = shift;
          $c->res->headers->header('Access-Control-Allow-Origin' => '*');
      }
  );

  $self->helper( dbh => sub {state $dbh = Mojo::SQLite->new('sqlite:db/mojo-ng.db') });
  $self->plugin(Minion => {SQLite => $self->dbh});
  $self->plugin('Minion::Admin');

  push @{$self->static->paths} => '/Users/Sachin/workspace/project/mojo_ng4/public/Demo';
  # Router
  my $r = $self->routes;
  $r->get('/Demo/hello')->to('Demo#hello');

  # Normal route to controller
  #$r->get('/Demo/index.html')->to('Demo#index');
  #$r->get('/Demo')->to('Demo#index');

}

1;

The magic line above is:

 push @{$self->static->paths} => '/Users/Sachin/workspace/project/mojo_ng4/public/Demo';

In Controller:

package MojoNg4::Controller::Demo;

use Mojo::Base 'Mojolicious::Controller';

# This action will render a template
sub index {
  my $self = shift;

  # render demo app index page. rest of the routes will be taken care by
  # angular4
  $self->reply->static('Demo/index.html');
}

1;

Magic line is:

$self->reply->static('Demo/index.html');

I have a git repo demonstrating how angular project can be served using Mojolicious. Please have a look: https://github.com/tryorfry/mojolicious-ng4