Today was my first attempt at learning Node.js and creating a basic server to display a single page with a header tag. However, I encountered an error stating that the CSS file could not be loaded.
This is the code I used:
const express = require('express');
const path = require('path');
const HOST = '127.0.0.1';
const PORT = 3000;
const app = express();
//app.use("/public", express.static(path.join(__dirname, "static")));
app.get('/', (request, response) => {
response.setHeader("Content-Type", "text/html");
response.sendFile(path.join(__dirname, "static", 'index.html'));
});
app.listen(PORT, HOST, () => {
console.log(`Running Server on ${HOST}:${PORT}`)
});
The HTML file:
<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>Hello World!</title>
<link rel="stylesheet" type="text/css" href="./css/index.css">
</head>
<body>
<h1>Hello World From Node.js!</h1>
</body>
</html>
The Error: https://i.sstatic.net/kCU6u.png
File Tree:
https://i.sstatic.net/ygM1J.png
I am in need of guidance to understand what might be missing for the CSS file to be properly linked with the HTML.
Note: The CSS file loads correctly when directly opening the HTML file in a browser.