Files in assets folder are not loaded on sub pages
I have a folder structure as shown below
-
assets
- bootstrapping
- CSS
- style.css
- Js
- jquery.min.js
- Views
- overtones
- head.ejs
- header.ejs
- scripts.ejs
- home.ejs
- user_registration.ejs
- overtones
In my app.js file I have set this assets folder as:
var app = express();
app.use('/static', express.static('assets'));
var routes = require('./routes/routes');
In 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 the user_registration file, I have the following code
<!DOCTYPE html>
<html lang="en">
<head>
<% include partials/head.ejs %>
</head>
<body>
<% include partials/scripts.ejs %>
</body>
</html>
Using this jQuery of mine the boot files that are in the assets folder are not getting loaded. But the home.ejs page works fine.
When I check in the console the home.ejs page accepts these files in the following format
http: // localhost: 3000 / static / bootstrap / css / bootstrap.min.css
whereas the custom registration page takes the following format
http: // localhost: 3000 / user_registration / static / bootstrap / css / bootstrap.min.css
I am very new to the express.js framework so I couldn't figure out how to solve this problem. Can someone please help me. Thank.
source to share
The problem here app.use('/static', express.static('assets'));
is your code line.
Replace it
app.use(express.static(path.join(__dirname, 'assets')));
AND in your head.ejs file replace the bootstrap css call line href="static/bootstrap/css/bootstrap.min.css"
to href="/bootstrap/css/bootstrap.min.css"
Remember you understand.
source to share
The problem is that a reference href
to a static resource must be absolute, not relative. Specifically, head.ejs
this should include:
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 stated app.use('/static', express.static('assets'));
, static assets are hosted in a namespace /static
(absolute url starting with /static
), it doesn't make sense to use a relative url anymore.
source to share