As I delve into pure node.js, I encountered an issue related to the HTTP protocol. After spending hours searching and testing my code, I finally managed to serve my HTML page with CSS successfully. Take a look at my code snippet below:
const server = http.createServer((req, res)=>{
if(req.url === "/"){
fs.readFile("index.html", "UTF-8", function(err, data){
res.writeHead(200, {"Content-Type": "text/html"});
res.end(data);
});
}else if(req.url === "/styles.css")){
var cssPath = path.join(__dirname, 'public', req.url);
var fileStream = fs.createReadStream(cssPath, "UTF-8");
res.writeHead(200, {"Content-Type": "text/css"});
fileStream.pipe(res);
};
});
However, I'm puzzled by how it works. When I only type "/" in the browser and not "/styles.css," why does the CSS still display without seeing "/styles.css" in the URL bar? I suspect it has something to do with the design of the HTTP protocol. Can anyone provide insight or explanation on this matter? Thank you!