Using app.use()
with middleware express.static(carpeta)
express exposes or mounts folder to the root of the server.
The line:
app.use(express.static(path.join(__dirname + '/public/css')));
Make all the files in __dirname + '/public/css'
accessible from http://localhost:3000/
, meaning that for the html to work, you should change it to:
<link rel="stylesheet" href="index.css" type="text/css">
To have the css (or other static files) in its own folder, it is usually advisable to mount them in a predefined path by specifying a static middleware for the path (using the first and second parameters of use
), for example:
server.js
const IMG_DIR = path.join(__dirname + '/assets/imagenes/');
const CSS_DIR = path.join(__dirname + '/public/css/');
app.use('/img', express.static(IMG_DIR));
app.use('/css', express.static(CSS_DIR));
index.html
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="/css/index.css" type="text/css">
</head>
<body>
<h1>hola</h1>
<img src="/img/imagendeprueba.png" />
</body>
</html>
In this example imagendeprueba.png
is in the folder assets/imagenes/
but when mounted on /img
, from the html (the client) is accessed by /img/imagendeprueba.png
File structure:
$ tree express_static/ -L 4 -I node*
express_static/
├── assets
│ └── imagenes
│ └── imagendeprueba.png
├── package-lock.json
├── public
│ └── css
│ └── index.css
├── routes
│ └── routes.js
├── server.js
└── views
└── index.html
Complete example:
server.js
const express = require("express");
const app = express();
const morgan = require("morgan");
const path = require("path");
// render engine
app.set('views', path.join(__dirname, 'views'));
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html')
//ROUTES
app.use(require("./routes/routes"));
//STATIC FILES
//app.use(express.static(path.join(__dirname + '/public/css')));
const IMG_DIR = path.join(__dirname + '/assets/imagenes/');
const CSS_DIR = path.join(__dirname + '/public/css/');
app.use('/img', express.static(IMG_DIR));
app.use('/css', express.static(CSS_DIR));
// server up
app.set('port', 3000);
const server = app.listen(app.get('port'), () =>
console.log('Example app listening on port '+ server.address().port)
);
views/index.html
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="/css/index.css" type="text/css">
</head>
<body>
<h1>hola</h1>
<img src="/img/imagendeprueba.png" />
</body>
</html>
installed packages:
$ npm ls --depth 0
/home/code/SO/express_static
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
└── [email protected]