0

my Node.js server seems to work fine, but recently I have noticed that my CSS does not go through the server. On inspect element, on sources tab I can see that it is there, but its is not being read. I think that my server.js file needs some changes. If someone could let me know how to improve my code, that would be fantastic.

const http = require('http');
const fs = require('fs');
const hostname = '127.0.0.1';
const port = 3000;

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/html');
  fs.readFile(__dirname + req.url,function(error,data){
    if (error){
      res.writeHead(404,'File not found!');
    }else {
      res.write(data)
    }
    res.end()
  })
});

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});
Felek
  • 3
  • 2

1 Answers1

0

That's going to think everything is html. If your server is going to simply accept file names for the url's then at least you have to read the extensions type and set the content type based on that:

fs.readFile(__dirname + req.url,function(error,data){

    if (error){
        res.writeHead(404,'File not found!');
        return;
    } 

    let cType = // probably convert this to switch logic
          res.url.endsWith('.css') ? 'text/css' 
        : res.url.endsWith('.html') ? 'text/html'
        : '';

    if (cType == '')
        res.writeHead(500, 'Extension not recognized');

    res.writeHead(200, {'Content-Type': cType});
    res.write(data);
    res.end();

});

But you'll probably want to take some of that logic outside of readFile as your server gets more complicated.

pwilcox
  • 5,542
  • 1
  • 19
  • 31