Lately, I've been struggling with serving CSS using Express.js. After some trial and error, I managed to make it work. However, I'm puzzled as to why my new code works while the old one doesn't. Here's the code that now works for me:
const express = require('express');
const path = require('path');
const app = express();
const port = process.env.PORT || 5010;
console.log(__dirname)
app.use('/public', express.static('public'));
app.set('views', path.join(__dirname, 'views'))
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'views', 'home.html'));
});
app.listen(port, () => {
console.log(`Server started on port ${port}`);
});
This is how my file system is structured:
index.js
public
css
home.css
views
home.html
Instead of my previous code:
app.use(express.static(path.join(__dirname, 'public')));
I had this working version:
app.use('/public', express.static('public'));
Could you explain why the second version works but not the first one? What role does the first parameter play in the second version? Just so you know, I'm coding on replit.com.