0

I'm starting out using Node.js and this is what I have so far...

server.js

var http = require('http');
const PORT = 3000; 

var fs = require('fs'),
    path = require('path'),    
    filePath = path.join(__dirname, 'index.html');

fs.readFile(filePath, {encoding: 'utf-8'}, function(err, html) {
    if (err) throw err;    

    http.createServer(function(request, response) {  
        response.writeHeader(200, {"Content-Type": "text/html"});  
        response.write(html);  
        response.end();  
    }).listen(PORT);

    console.log("Server successfully hosted at http://127.0.0.1:" + PORT + "/");
});

index.html

<!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">
  <link rel="stylesheet" type="text/css" href="styles.css">
  <title>My First Node.js!</title>
</head>
<body>
  <h1>Hello there!</h1>
  <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Rem perferendis ratione itaque, alias nesciunt nemo porro deserunt animi iusto dolor?</p>
</body>
</html>

styles.css

*, *::before, *::after {
  box-sizing: border-box;
}

h1 {
  text-align: center;
}

p {
  text-align: center;
}

However, when I run the server, none of my CSS styles are showing up. When I used google Dev tools to check, my CSS file had the HTML code in it?

Dev Tools Sources Screenshot

My guess is that the HTML <link rel="stylesheet" type="text/css" href="styles.css"> is somehow creating a CSS file instead of finding the file?

Please let me know if there's any way to fix this.

Thanks.

Llamaful
  • 23
  • 6
  • 2
    You setup the server to return the HTML on any request. When you request "style.css", it still returns the HTML because that's what you told your server to do. – Aioros Apr 08 '22 at 16:13
  • Having `createServer` inside the `readFile` callback doesn't seem right. Create and launch the server, and then use endpoints that your client can access. Something [like Express](https://expressjs.com/) might take the headache out of that. – Andy Apr 08 '22 at 16:17

0 Answers0