sanin
sanin

Reputation: 274

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

I have a folder structure like below

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.

Upvotes: 4

Views: 3970

Answers (2)

shaochuancs
shaochuancs

Reputation: 16266

The problem is: the href link to static resource should be absolute, not relative. Specifically, in head.ejs it should be:

href="/static/bootstrap/css/bootstrap.min.css"
...
href="/static/css/style.css"

NOT:

href="static/bootstrap/css/bootstrap.min.css"
...
href="static/css/style.css"

As app.use('/static', express.static('assets')); stated, the static assets are hosted under /static namespace (absolute URL starting with /static), it doesn't make any sense to use relative URL any more.

Upvotes: 1

Viran Malaka
Viran Malaka

Reputation: 427

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.

Upvotes: 4

Related Questions