Currently, I am setting up the back-end structure for my website. The file setup looks like this:
public
css
main.css
main_b.css
index.hbs
index_b.hbs
server
server.js
To reference style sheets in the index files, I use link attributes with:
rel="stylesheet" type="text/css" href="main.css"
rel="stylesheet" type="text/css" href="main_b.css"
My server.js script is as follows:
const path = require('path');
const fs = require('fs');
const express = require('express');
const app = express();
const hbs = require('hbs');
hbs.registerPartials(path.join(__dirname, '../public/partials'));
app.set('view engine', 'hbs');
app.use(express.static(path.join(__dirname, '../public/css')));
// activity logger
app.use((req, res, next) => {
const now = new Date().toString();
const logEntry = `${now}: ${req.headers.host} ${req.method}${req.url}`;
fs.appendFile(path.join(__dirname, '../server/server.log'), logEntry.concat('\n'), (error) => {
if (error) {
console.log(error);
}
});
process.env.route = req.path;
next();
});
app.get('*', (req, res) => {
switch (process.env.route) {
case '/': // home page
res.render('../public/index.hbs');
break;
case '/b': // basic layout
res.render('../public/index_b.hbs');
break;
default: // unknown routes
res.render('../public/index.hbs');
}
});
app.listen(3000);
When requesting localhost:3000, the log entry is accurate:
Thu Jan 24 2019 07:57:08 GMT+0200 (Eastern European Standard Time): localhost:3000 GET/
Similarly, when accessing localhost:3000/abc, the log reflects the request:
Thu Jan 24 2019 07:57:08 GMT+0200 (Eastern European Standard Time): localhost:3000 GET/abc
However, issues arise when testing sub-routes like localhost:3000/abc/def. The CSS doesn't render correctly and the log shows:
Thu Jan 24 2019 08:04:55 GMT+0200 (Eastern European Standard Time): localhost:3000 GET/abc/def Thu Jan 24 2019 08:04:56 GMT+0200 (Eastern European Standard Time): localhost:3000 GET/abc/teamk-reset.css Thu Jan 24 2019 08:04:56 GMT+0200 (Eastern European Standard Time): localhost:3000 GET/abc/main.css
I've attempted to adjust the CSS lookup path using the index and redirect properties of the options object in Express.static(), but have not succeeded.
Any guidance or references on resolving this issue would be greatly appreciated. Otherwise, I may need to reconsider my approach to route querying.