Search code examples
perlmojoliciousmojolicious-lite

Mojolicious gives 404 when getting JS and CSS


I'm new to Mojolicious, and I've got various things working, but I've come up against a problem which I've recreated in the following minimal bit of code.

The problem is a simple one: I can't get it to load external CSS and JS files. What surprises me is that it gives 404 errors as though it's trying to serve these static files as routes. No-one else seems to be having this problem, so I've obviously done something (or missed something) foolish.

The files in question are in the ./css and ./js directories relative to the perl file (errorddemo.pl). I've tried with and without the leading '/', and any other variations that I could think of.

This is the code:

#!/usr/bin/env perl
use Mojolicious::Lite;
get '/' => sub {
    my $c = shift;                                                     
    $c->render('index');
};            
app->start;

__DATA__
@@ index.html.ep
<!DOCTYPE html>
<html>
    %= stylesheet '/css/bootstrap-3.3.2-dist/css/bootstrap.css'
</head>      
<body>
    <p>blah
    %= javascript '/js/jquery-2.1.3.js'
</body>     
</html>

When I run morbo errordemo.pl and browse to :3000, I get this:

[Sun Jan 25 00:24:04 2015] [debug] GET "/".
[Sun Jan 25 00:24:04 2015] [debug] Routing to a callback.
[Sun Jan 25 00:24:04 2015] [debug] Rendering template "index.html.ep" from DATA section.
[Sun Jan 25 00:24:04 2015] [debug] 200 OK (0.005127s, 195.046/s).
[Sun Jan 25 00:24:04 2015] [debug] GET "/css/bootstrap-3.3.2-dist/css/bootstrap.css".
[Sun Jan 25 00:24:04 2015] [debug] Template "not_found.development.html.ep" not found.
[Sun Jan 25 00:24:04 2015] [debug] Template "not_found.html.ep" not found.
[Sun Jan 25 00:24:04 2015] [debug] Rendering inline template "3e3201ab0667c1fc7f39089209f0435c".
[Sun Jan 25 00:24:04 2015] [debug] Rendering inline template "b2d451b47e2053ce583cbfdf7bcc6006".
[Sun Jan 25 00:24:04 2015] [debug] 404 Not Found (0.045663s, 21.900/s).
[Sun Jan 25 00:24:04 2015] [debug] GET "/js/jquery-2.1.3.js".
[Sun Jan 25 00:24:04 2015] [debug] Template "not_found.development.html.ep" not found.
[Sun Jan 25 00:24:04 2015] [debug] Template "not_found.html.ep" not found.
[Sun Jan 25 00:24:04 2015] [debug] Rendering cached inline template "3e3201ab0667c1fc7f39089209f0435c".
[Sun Jan 25 00:24:04 2015] [debug] Rendering cached inline template "b2d451b47e2053ce583cbfdf7bcc6006".
[Sun Jan 25 00:24:04 2015] [debug] 404 Not Found (0.009863s, 101.389/s).

The generated HTML is:

<!DOCTYPE html>
<html>
    <link href="/css/bootstrap-3.3.2-dist/css/bootstrap.css" rel="stylesheet" />
</head>
<body>
    <p>blah
    <script src="/js/jquery-2.1.3.js"></script>
</body>


Solution

  • Static files are served from ./public, relative to the lite app (errorddemo.pl).

    You can specify other folders by modifying the array refererence at app->static->paths:

    push @{app->static->paths} => '.';