I'm facing an issue with my Express app where the static files are not working properly for certain routes. For example, when I visit '/', all styles and images load correctly as expected when the index.ejs is rendered. However, when I navigate to a non-existent route like '/efbhew', the 404.ejs page renders fine but the static assets do not load. Similarly, for routes like '/asdw/feff' or '/df/fg/dfgdfg/sfgd', the static resources fail to load. Is there something missing in my setup that I need to address?
Below is an excerpt from my code:
const app = express();
app.use(express.static(path.join(__dirname, '../public')));
app.set('views', path.join(__dirname, '../views'));
app.set('view engine', 'ejs');
app.use(cors());
app.use(express.json());
app.get('/', async (req, res) => {
const posts = await Post.find({}).limit(7).sort({ createdAt: -1 }).exec();
res.render('index.ejs', {
latestPosts: posts
});
});
app.get('*', (req, res) => {
res.render('404.ejs');
});
This is the current folder structure of my project:
https://i.sstatic.net/Wn0X7.png
I have attempted adjusting the path to the public folders to accommodate deeper paths such as '/asdf/wfds/img/logo.png', however, this did not resolve the issue.