express global middleware not being called

2020-08-09 07:22发布

问题:

As far as I can tell I'm configuring my global middleware function as described in the docs and in every forum post on the subject, but it is not being called. Does anyone see what I'm doing wrong? express 3.2.5. In the log output I see the following:

Express server listening on port 9000
inside route
GET / 200 7ms - 2b

I expect to see "inside middleware", then "inside route". Instead, I just see "inside route".

The code:

var express = require('express'), http=require('http'), path=require('path');

var app = express();

app.enable('trust proxy');

app.set('port', process.env.PORT || 9000);
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.set('layout', 'layout');

app.use(require('express-ejs-layouts'));
app.use(express.favicon(__dirname + '/public/images/favicon.ico')); 
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride())
app.use(express.cookieParser('kfiwknks'));
app.use(express.session());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));

if ('development' == app.get('env')) {
  app.use(express.errorHandler());
} else {
  app.use(function(err, req, res, next){
    console.error (error);
    res.send (500, "Internal server error");
  });
}

app.use (function (req, res, next) {
  console.log ("inside middleware");
  next();
});

app.get ("/", function (req, res) {
  console.log ("inside route");
  res.send(200);
});

http.createServer(app).listen(app.get('port'), function() {
  console.log('Express server listening on port ' + app.get('port'));
});

This related post:

Express 3 error middleware not being called

is specific to error handling middleware. Mine is a vanilla middleware.

回答1:

You should put your middleware before you use app.router.

...
app.use (function (req, res, next) {
  console.log ("inside middleware");
  next();
});
...
app.use(app.router);


回答2:

Updated answer for Express 4 users from the Express 4 docs. See example from docs below. Note that app.router is deprecated and no longer used. I also added a dummy route to make the ordering clear.

You define error-handling middleware last, after other app.use() and routes calls

Example:

var bodyParser = require('body-parser');

app.use(bodyParser());

app.get('/', function(req, res) {
    res.send('hello world');
})

app.use(function(err, req, res, next) {
  // logic
});