I am actually facing this problem in another bigger project but, I have made a simple one so as to explain it easily
Tree Structure of my project is as follows
demo
|____admin
| |____admin.js
|____node_modules
|
|____static
| |____bootstrap.min.css
| |____headerStyle.min.css
|
|____views
| |____admin
| | |____admin_home.ejs
| |
| |____partials
| |____admin_header.ejs
|
|____index.js
|____package-lock.json
|____package.json
please bear with me, I am going to post the code of some of important files
code in 'index.js' is this
let express = require('express');
let app = express();
let path = require('path');
app.use(express.static(path.join(__dirname, 'static')));
app.set('view engine', 'ejs');
app.get('/',function(req,res)
{
res.render('./admin/admin_home');
});
let admin = require('./admin/admin.js');
app.use('/admin',admin);
app.listen(9000,function(){
console.log('listening to port : 9000');
});
Code in 'admin/admin.js' is this
let express = require('express');
let router = express.Router();
router.get('/',function(req,res)
{
res.render('./admin/admin_home');
});
router.get('/adminhome',function(req,res)
{
res.render('./admin/admin_home');
});
module.exports = router;
Code in 'views/admin/admin.ejs' is this
<%- include('../partials/admin_header.ejs') %>
<h1>Admin Home</h1>
I am having problem with express js static file serving.
For the following URL's the webpages are rendered with all the styles from css files
http://localhost:9000
http://localhost:9000/admin
they are served from these paths
http://localhost:9000/bootstrap.min.css
and
http://localhost:9000/headerStyle.css
but for the following URL webpages are rendered with plain html with out serving the css syles
http://localhost:9000/admin/adminhome
the error is
Failed to load the resources: the server responded with 404
css files are served from these paths
http://localhost:9000/admin/bootstrap.min.css
and
http://localhost:9000/admin/headerStyle.css
and the 'Link' tags in 'vies/partials/admin_header.ejs' are as follows
<link rel="stylesheet" type="text/css" href="bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="headerStyle.css">
versions of the modules are as follows
ejs:^2.5.7
express:^4.16.2
path:^0.12.7
my nodejs version is v8.5.0
Please help me in finding the solution for this problem. Thank You
hrefof your styles are relative to the url you are visiting. You can make them absolute like:href="/bootstrap.min.css".