I can't use EJS layout using res.render()

1.2k Views Asked by At

I've been trying to use express-ejs-layouts module. My when I try second route, browser finds my JS and CSS resource file under my second EJS files -that was written by me into second route function.

What should I do?

My Layout appears properly with my first route process like the following.

my first route;

app.get('/', function(req, res) {
        res.render('home/index');
});

my layout.ejs file;

<!DOCTYPE html>
<html lang="tr">
<head>
    <link rel="stylesheet" href="bootstrap/css/bootstrap.css">
    <link rel="stylesheet" href="css/styles.css">    
</head>
<body>

    <% include navbar %>

    <%- body %> 

    <script src="js/jquery.js"></script>
    <script src="bootstrap/js/bootstrap.js"></script>

</body>
</html>

So far everything is good. My resource files (css and js) linked and I can see my home/index.ejs properly. And then I try my second route like the following;

my second route;

app.get('/user/:id', function(req, res) {
     res.render('user/index');
});

My browser console gives the below errors;

Failed to load resource: the server responded with a status of 404
(Not Found) http://localhost:1337/user/bootstrap/css/bootstrap.css

Failed to load resource: the server responded with a status of 404
(Not Found) http://localhost:1337/user/css/styles.css

Failed to load resource: the server responded with a status of 404
(Not Found) http://localhost:1337/user/js/jquery.js

Failed to load resource: the server responded with a status of 404
(Not Found) http://localhost:1337/user/bootstrap/js/bootstrap.js
1

There are 1 best solutions below

1
On BEST ANSWER

Express needs a 'public' named folder to check resources. So I've put my resources files into a ".../public/" folder, rewrote src link and I got succeed.

I've defined a new static path;

app.use(express.static(__dirname + '/public'));

An then I changed my new layout.ejs file like the below;

<!DOCTYPE html>
<html lang="tr">
<head>
    <link rel="stylesheet" href="/css/bootstrap.css">
    <link rel="stylesheet" href="/css/styles.css">    
</head>
<body>

    <% include navbar %>

    <%- body %> 

    <script src="/js/jquery.js"></script>
    <script src="/js/bootstrap.js"></script>

</body>
</html>