Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

205
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda