Soy nuevo en el nodo y estoy tratando de cargar un archivo css simple al iniciar una aplicación de nodo simple. La cuestión es que css se carga cuando simplemente abro index.html directamente en un navegador.
Estructura del proyecto:
├── node │ └── app │ ├── app.js │ ├── index.html │ ├── server.js │ └── styles │ └── style.css Puedo abrir style.css haciendo clic en href en el archivo html, entonces, ¿por qué no se carga cuando llamo a localhost: 8080?
La pestaña Respuesta muestra el archivo html, por lo que parece estar apagado. ¿Debería mostrar eso?
aplicación.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); });estilo.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; }índice.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>El servidor ahora está enviando un solo archivo, pero necesita leer y enviar cada archivo solicitado, es decir, necesita servir archivos estáticos.
Para hacer eso, puede verificar la URL solicitada y leer el archivo, como se explica aquí:
https://nodejs.org/en/knowledge/HTTP/servers/how-to-serve-static-files/
También verifique diferentes soluciones para servir archivos estáticos:
Pruebe esto, registrará todos los archivos solicitados en la consola. Además, para que index.html funcione, debe escribir http://localhost:8080/index.html . Para evitar eso, podemos capturar la ruta / y enviar ese archivo en esa ruta, por lo que http://localhost:8080 servirá index.html , por lo que también tenemos un poco de enrutamiento.
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); Sin embargo, puede notar que el ejemplo no escribe un encabezado content-type , por lo que debe verificar cada solicitud, detectar el tipo MIME y agregar el encabezado, lo que requiere código adicional, y por eso es mejor usar bibliotecas que haz eso fuera de la caja.