Reputation: 186013
I'm reading the two examples in the Express.js API reference but I don't get them.
Now suppose you wanted to ignore logging requests for static files, but continue logging routes and middleware defined after logger(). You could simply move static() above it:
app.use(express.static(__dirname + '/public'));
app.use(logger());
// other middleware
How does this cause requests for static files not to be logged? Isn’t all middleware executed (in sequence) for every request?
Another concrete example would be serving files from multiple directories, giving precedence to "./public" over the others:
app.use(express.static(__dirname + '/public'));
app.use(express.static(__dirname + '/files'));
app.use(express.static(__dirname + '/uploads'));
I suspect that for e.g. a request like "/js/stuff.js", the first middleware checks if "/public/js/stuff.js" exists. If it does, this middleware handles the request and none of the subsequent middleware is executed (sort-of like an early return). If this path however doesn't exist, this middleware passes the request to the next middleware in line. Is this correct?
Please explain both examples!
Upvotes: 1
Views: 1361
Reputation: 17444
Express routes are just a collection of middleware. Every request to the server is passed along the middleware chain.
A middleware function has the signature
function(req, res, next) { }
You can add middleware to the chain with app.use()
, as you've seen above.
Each middleware has two choices. It can
If a middleware fails to do either of these, you'll see your request time out and just "spin" endlessly.
To pass a request along, the middleware must call next()
. The third argument passed to a middleware is this next()
function. It might have a side effect, like the logger middleware above.
To end a request, the middleware can use one of several methods attached to the res
object, such as res.send()
or res.end()
to send a response back to the requestor. So the express.static
middleware has the behavior that, if it finds the requested file, it ends the request chain and sends the file. If it doesn't find the requested file, it passes the request to the next middleware.
Upvotes: 5