Create routes for node and Express server

0

I am creating a server with node, which is the following:

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

app.get('/',function(request,res){
    res.sendfile('/index.html');
});

app.listen(3000,function(){
  console.log('El servidor Esta En llamas!');
});

The file is called server.js and is in the Challenge folder together with the index.html. Inside the same folder I have the folder / css, / js, / img and etc ...

The thing is that I need to import these from your location so you can have everything running ....

As correpsonde routs the folders in node and on express?

regards ...

    
asked by Hernan Humaña 14.03.2017 в 20:38
source

1 answer

4

It's quite simple, first of all, correct your code so that it looks like this:

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

// Para llamar los archivos css y js públicos desde tu index.html debes
// declarar las rutas como estáticas de la siguiente forma
app.use('/public/css', express.static(__dirname + '/css'));
app.use('/public/js', express.static(__dirname + '/js'));
app.use('/public/img', express.static(__dirname + '/img'));

app.get('/',function(request,res){
    // el método es sendFile (con F mayúscula) y debes agregar
    // la variable de entorno llamada __dirname que te da la ruta de 
    // de la raíz en tu actual proyecto
    res.sendFile(__dirname + '/index.html');
});

app.listen(3000, function(){
  console.log('El servidor Esta En llamas!');
});

Then in your index.html you can access your folders css , js e img in the following way:

<!DOCTYPE HTML>
<html>

<head>
    <title></title>
    <link rel="stylesheet" href="./public/css/mi_archivo_css.css">
    <script src="./public/js/mi_archivo_js.js"></script>
</head>
<body>
    <img src="./public/img/mi_imagen.jpg" />
</body>
</html>
    
answered by 14.03.2017 / 20:44
source