I was trying to use a CSS file in my node.js server, but it never show up on the webpage. I'm doing this on Visual Studio Code 2019.
'use strict';
var http = require("http");
var express = require("express");
var app = express();
var path = require("path");
var fs = require("fs");
var port = process.env.PORT || 1337;
http.createServer(function (req, res) {
res.writeHead(200, { "Content-Type": "text/html" });
fs.readFile("index.html", function (error, data) {
if (error) {
res.writeHead(404)
res.write("Error: File Not Found")
}
else {
app.use(express.static(path.join(__dirname, "/public")));
res.write(data)
}
res.end();
})
}).listen(port);
And on my HTML file I did:
<link rel="stylesheet" href="/main.css">
The webpage only shows my HTML, but it pretended my CSS code never existed, so it's just a bunch of plain text. I'm still relatively new to node.js so I might just be missing a few simple things.
Directory:
- public (folder)
- main.css
- index.html
- server.js