Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Files inside the assets folder are not being loaded in sub pages

I have a folder structure like below

  • assets

    • bootstrap
    • css
      • style.css
    • js
      • jquery.min.js
  • views
    • partials
      • head.ejs
      • header.ejs
      • scripts.ejs
    • home.ejs
    • user_registration.ejs

In my app.js file I have set this assets folder like:

var app = express();
app.use('/static', express.static('assets'));
var routes = require('./routes/routes');

In my routes.js file

exports.userLogin = function(req, res){
    var userLogin = req.params.userId;
    var users = memberData.users;
    res.render('user_registration', {
        title : 'Welcome',
        users : users
    });
};

In my head.ejs file

<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="static/bootstrap/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<link href='https://fonts.googleapis.com/css?family=Montserrat:400,700' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">
<link rel="stylesheet" href="static/css/style.css" type="text/css">

Now inside in user_registration file, I have following code

<!DOCTYPE html>
<html lang="en">
<head>
    <% include partials/head.ejs %>
</head>
<body>
    <% include partials/scripts.ejs %>
</body>
</html>

By using this my jQuery, bootstrap files that are inside assets folder are not being loaded. But the home.ejs page is working normally.
When I check at the console, the home.ejs page is taking those files in following format http://localhost:3000/static/bootstrap/css/bootstrap.min.css

whereas user_registration page is taking following format

http://localhost:3000/user_registration/static/bootstrap/css/bootstrap.min.css

I am very new in express.js framework, so I could not figure out how to solve this problem. Can anybody please help me. Thank you.

like image 816
sanin Avatar asked Sep 18 '25 23:09

sanin


1 Answers

Problem is here app.use('/static', express.static('assets')); in your code line.
Replace it with app.use(express.static(path.join(__dirname, 'assets')));
And in your head.ejs file replace bootstrap css calling line
href="static/bootstrap/css/bootstrap.min.css" to href="/bootstrap/css/bootstrap.min.css"

Hop you understand.

like image 162
Viran Malaka Avatar answered Sep 21 '25 17:09

Viran Malaka