简体   繁体   中英

ExpressJS app.use

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'));
});

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM