Does using app.use(express.static("public"))
call the middleware for every request, even if it wasn't a request for a static resource?
When registering it like that it, the middleware will run on every request, yes. Basically because that statement is actually the same as:
app.use("/", express.static("public"))
Calling express.static
returns a classic middleware function that will be run on every path you specify in app.use
. If you want it only to kick in on a specific path, you could register it like this:
app.use('/static', express.static('public'));
It will only get called if a route hasn't dealt with the request already.
Keeping in mind that routes are tested in the order they are registered, take this example:
const express = require('express');
const app = express();
const port = 3000;
app.get('/foo', (req, res) => {
console.log('Foo!');
res.send('Foo!');
});
app.use(function (req, res, next) {
console.log('middleware triggered');
next();
});
app.get('/bar', (req, res) => {
console.log('Bar!');
res.send('Bar!');
});
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`);
});
If I request http://localhost:3000/foo
then the server will log:
Foo!
The /foo
endpoint matched the request and then called res.send()
.
If I request http://localhost:3000/bar
then it logs:
middleware triggered
Bar!
The middleware kicks in (because it matches the route), called next()
to go to the next function that matches the route, and then the /bar
handler is called.
It is important to position your static
middleware carefully.
If you put it before the route you want to match the request then there are two possible negative effects:
On the other hand, if you put it last then you'll solve the efficiency problem, but some bad route design might mean that something creates a URL which matches an already existing static file and masks it.
It's a good idea to specify a directory that you know will never conflict with a route (eg app.use('/static', express.static('public'));
) to avoid that possibility. As a bonus it means that any broken links which would normally 404 won't have to go through the static middleware unless the link is pointing in the /static
path in the first place.
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.