简体   繁体   中英

The server stops working if I wrap express.static in a function

the code below works:

var express = require('express');
var path  = require('path');
var app = express();
app.use('/public', express.static("./public"));
app.listen(3000, function () {
    console.log('Example app listening on port 3000!');
});

But if I change the app.use like this:

var express = require('express');
var path  = require('path');
var app = express();
app.use('/public', function(){express.static("./public")}); 
// browser error "cannot GET /
app.listen(3000, function () {
    console.log('Example app listening on port 3000!');
});

Why? The server doesn't seem to catch any errors

express.static() returns a middleware function when you call it. You have to pass that specific returned function to app.use() . You don't just call express.static() on every request. You call it once, get the returned function and register that as middleware and app.use() will then call that middleware function on every request.


When you do it the correct way like this:

app.use('/public', express.static("./public"));

It's like doing this:

const fn = express.static("./public");
app.use('/public', fn);

or even like this:

const fn = express.static("./public");
app.use('/public', function(req, res, next) {
    fn(req, res, next);
});

Hopefully you can see that this code:

app.use('/public', function(){express.static("./public")}); 

does not do the same thing as any of the correct solutions. This calls express.static() in every request and never calls the returned function that does the actual work for a given request.


Think of express.static("./public") like a factory function. It creates a middleware function that you then pass to app.use() or call yourself with req , res and next as the arguments.

Why? The server doesn't seem to catch any errors

Executing app.use('/public', function(){express.static("./public")}); is not what you want, but it also doesn't create an error. All it does is create a new middleware function (which you ignore) on every single request. It also never calls next to let any other request handlers handle the request so your server would get stuck on every request, but it never actually causes a visible error.

It essentially becomes functionally equivalent to this:

app.use('/public', function(req, res, next) {
   // do nothing, just causes the request to get stuck since
   // the request is not handled (no response is sent)
   // and next is never called
});

The request is never handled and never calls next to advance to other route handlers so the request just gets stuck and will eventually time out.

您可以尝试:

  app.use(express.static(path.resolve(__dirname, './public'), { maxAge: '1d' }));

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