Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

204
Visualizações
css not being executed in node

I am new to node and am trying to get simple css file to load upon starting a simple node app. Thing is, css does load when I simply open index.html directly in a browser.

Project structure:

├── node
│   └── app
│       ├── app.js
│       ├── index.html
│       ├── server.js
│       └── styles
│           └── style.css

I can open style.css by clicking on the href in the html file, so why doesn't it load when I call localhost:8080?

The Response tab shows the html file, so that seems off. Should it show that?

app.js

var http = require('http');
var fs = require('fs');

const PORT=8080; 

fs.readFile('./app/index.html', 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);
});

style.css

. {
    box-sizing: border box;
}
html, body {
    height: 100%;
    width: 100%;
}
body { 
    margin: 0;
    border: 5px solid blue;
}
#container {
    margin: 3% 10% 0 5%;
    border: 2px solid #dddddd;
}

index.html

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>index</title>
        <link rel="stylesheet" type="text/css" href="styles/style.css">
    </head>
    <body>
         <div id="container">
            <div>
                <h1 class="title">Title</h1>
            </div>
        </div>
    </body>
</html>
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

The server is now sending a single file, but you need to read and send every requested file, i.e. you need to serve static files.

To do that, you can check requested URL and read the file, as explained here:

https://nodejs.org/en/knowledge/HTTP/servers/how-to-serve-static-files/

Also check different solutions for serving static files:

https://www.npmjs.com/package/node-static

https://expressjs.com/en/starter/static-files.html

Try this, it will log every requested file to the console. Furthermore, to get index.html to serve, you'd need to type in http://localhost:8080/index.html. To avoid that, we can catch the / route, and send that file on that route, so http://localhost:8080 will serve index.html, so we have a bit of routing too.

var fs = require('fs'),
  http = require('http');

http.createServer(function(req, res) {
  
  let file = req.url;

  // serve index.html on http://localhost:8080/
  if (file === '/') {
    file = '/index.html';
  }

  console.log('serving static file: ', file);

  // read every requested file, and send it to the browser   
  fs.readFile(__dirname + file, function(err, data) {

    if (err) {
      res.writeHead(404);
      res.end(JSON.stringify(err));
      return;
    }
    res.writeHead(200);
    res.end(data);
  });
}).listen(8080);

However, you can notice that the example doesn't write content-type header, so you'd need to check every request, detect mime type and add the header, which requires extra code, and which is why it's better to use libraries that do that out of the box.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda