【问题标题】:express global middleware not being called表示未调用全局中间件
【发布时间】:2013-07-15 10:59:08
【问题描述】:

据我所知,我正在按照文档和有关该主题的每个论坛帖子中的描述配置我的全局中间件功能,但它没有被调用。有谁看到我做错了什么?表达 3.2.5。在日志输出中,我看到以下内容:

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

我希望看到“内部中间件”,然后是“内部路由”。相反,我只看到“内部路线”。

代码:

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

此相关帖子:

Express 3 error middleware not being called

特定于错误处理中间件。我的是一个普通的中间件。

【问题讨论】:

  • 你需要require("path")
  • 谢谢 - 工作示例中需要路径。我在帖子中手动添加了require语句(并且刚刚在帖子中添加了路径)。如果不需要路径,代码就会简单地爆炸。
  • 在使用 app.router 之前放置中间件
  • 谢谢 - 把中间件放在 app.router 之前就成功了!
  • @user568109 请将其发布为答案,而不是评论,以便 Jake 接受。

标签: node.js express middleware


【解决方案1】:

你应该在使用app.router之前放置你的中间件。

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

【讨论】:

  • 非常感谢 - 这成功了!我的收获是 app.router 必须是在定义路由之前添加的最后一个全局中间件。
  • 谢谢!!它帮助了我。
  • app.router 在 4.x 中似乎已被弃用
  • 在我的情况下,我在 .listen 方法之后调用它,我在 express 的 4.17.1 上
【解决方案2】:

为 Express 4 用户 from the Express 4 docs 更新了答案。请参阅下面文档中的示例。请注意,app.router 已弃用,不再使用。我还添加了一个虚拟路线以明确排序。

在其他 app.use() 和路由调用之后,您最后定义错误处理中间件

示例:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-24
    • 1970-01-01
    • 2014-12-24
    • 1970-01-01
    • 2021-04-14
    • 1970-01-01
    相关资源
    最近更新 更多