Does not load CSS on NodeJS server

1

I have the following basic server:

var express = require('express');
var app = express();

app.get('/', function(req, res){
  res.sendfile(__dirname + '/public/index.html');
  });
  
app.listen(8081);

In that index.html I have reference to some CSS that are in the same public folder. The route is correct, because if I open the html with the browser I get the correct way, but if I enter through the server (ie localhost: 8081) I get the flat html, without the CSS. What do I have to add in my NodeJS server?

The CSS referenced from index.html in this way:

<link rel="stylesheet" href="assets/css/main.css" />
    
asked by Ibrahim Hernández Jorge 31.03.2017 в 19:34
source

1 answer

2

Try the following code, basically you would need to indicate to the app where the static files are located (css, js, images, etc.)

// Se cargan los modulos necesarios.
var express = require('express');
var path = require('path');

// Crea una Express app.
var app = express();

// obtiene la ruta del directorio publico donde se encuentran los elementos estaticos (css, js).
var publicPath = path.resolve(__dirname, 'public'); //path.join(__dirname, 'public'); también puede ser una opción

// Para que los archivos estaticos queden disponibles.
app.use(express.static(publicPath));

app.get('/', function(req, res){
  res.sendfile(__dirname + '/public/index.html');
  });

app.listen(8081);
    
answered by 31.03.2017 / 21:27
source