I’m currently working on a web project using Node.js and Express, and I’m facing an issue with my CSS not loading properly when serving the static files. I’ve tried using express.static, but it doesn’t seem to work as expected. Here’s a brief overview of my folder structure and code:
const express = require('express');
const fs = require('fs');
const path = require('path');
const app = express();
const port = 3000;
app.use(express.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname, '..', 'Public')));
app.post('/subscribe', (req, res) => {
const email = req.body.email;
fs.appendFile('subscribers.txt', email + '\n', (err) => {
if (err) throw err;
});
res.send('Thank you for subscribing!');
});
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, '..', 'Public', 'Home', 'Home.html'));
});
app.listen(port, () => {
console.log(`Server listening at http://localhost:${port}`);
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Home</title>
<link rel="stylesheet" type="text/css" href="Home.css">
<script src="https://kit.fontawesome.com/3720a64a77.js" crossorigin="anonymous"></script>
</head>
{
"name": "email-subscription",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.20.2",
"express": "^4.18.2"
}
}
I am new to coding, and so deeply appreciate any help/advice!
>Solution :
Your Express server is serving the whole Public
directory, but the CSS file Home.css
is in Public/Home/Home.css
, so you need to use the path Home/Home.css
(relative to the directory being served, not to the HTML file) to get your CSS file
Just change this line in your HTML:
<link rel="stylesheet" type="text/css" href="Home.css">
to this:
<link rel="stylesheet" type="text/css" href="Home/Home.css">