Reputation: 23
I'm trying to learn ExpressJS and I came across this piece of code. I just can't seem to understand the app.use function and the documentation is unclear to me. What exactly is happening to the /public directory in this particular example code when app.use is called?
// Require dependencies
var express = require('express');
var app = express();
// Set server port
app.set('port', (process.env.PORT || 3000));
// Set static page directory, /public
app.use(express.static(__dirname + '/public'));
app.use('/public', express.static('public'));
// Set template file directory, /views. Set view engine to EJS
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
// Route root request to pages/index
app.get('/', function(request, response) {
response.render('pages/index');
});
// Route favicon request to public/favicons
app.get('/favicon.ico', function(request, response) {
response.render('./public/favicons');
});
// Begin listening at specified port
app.listen(app.get('port'), function() {
console.log('Node app is running on port', app.get('port'));
});
Upvotes: 0
Views: 69
Reputation: 4328
It's simple - you are setting up the public directory to be accessible over HTTP.
So, something like http://localhost:3000/public/abc.jpg
will give you the abc.jpg
from the public folder.
The
app.use('/public', express.static('public'))
line simply means - match any path that starts with /public
like:
http://localhost/public/*.jpg
or any other extension - will choose that file from your public
(the argument in express.static('public')
) folder and serve it.
The line
app.use(express.static(__dirname + '/public'))
means - match any path and if file found in public
directory, serve it over HTTP.
You can just use of the these two lines - difference being the /public
part in the URL.
The docs are quite clear about this: https://expressjs.com/en/starter/static-files.html
Upvotes: 1