Currently, I am encountering this issue in a larger project, so I have created a simplified version to explain it more clearly.
The Tree Structure of my project is outlined below:
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
I appreciate your patience as I will be sharing the code from some key files.
The code in 'index.js' is as follows:
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');
});
The code in 'admin/admin.js' is as shown below:
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;
The code in 'views/admin/admin.ejs' is displayed here:
<%- include('../partials/admin_header.ejs') %>
<h1>Admin Home</h1>
I am facing an issue with ExpressJS static file serving.
For the following URLs, webpages render with all the CSS styles applied:
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
However, for the URL below, the webpage is rendered with plain HTML without the CSS styles being served:
http://localhost:9000/admin/adminhome
The error message states:
Failed to load the resources: the server responded with 404
The CSS files are served from these paths:
http://localhost:9000/admin/bootstrap.min.css
and
http://localhost:9000/admin/headerStyle.css
The 'Link' tags in 'vies/partials/admin_header.ejs' appear as:
<link rel="stylesheet" type="text/css" href="bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="headerStyle.css">
The module versions utilized are:
ejs:^2.5.7
express:^4.16.2
path:^0.12.7
My NodeJS version is v8.5.0.
Please assist me in resolving this issue. Thank you!