快速中间件被多次调用

时间:2017-06-22 09:16:26

标签: node.js express middleware

app.use(function(req, res, next) {
    var chatlog = [];
    console.log('executed many timews why?')   
 var chatlog = redisClient.lrange('messages', 0, 99, function(err, reply) {
        if (!err) {
            var result = [];
            for (var msg in reply) result.push(JSON.parse(reply[msg]));
            if (result.length == 0) { 
                result.push({
                    "msg": 'welcome',
                    "nickname": "guest1"
                })
            }
            console.log(result)
        } else {
            console.log('error getting chat messages')
        }
        res.locals = {
            chatlog: result
        };
        next();
        return
    });

  app.get('/', (req, res) => {
 res.render('index', {     })
  })

当我访问'/'一次时,控制台会打印以下内容:

executed many timews why
[ { msg: 'welcome', nickname: 'guest1' } ]
executed many timews why
executed many timews why
executed many timews why
executed many timews why
[ { msg: 'welcome', nickname: 'guest1' } ]
[ { msg: 'welcome', nickname: 'guest1' } ]
[ { msg: 'welcome', nickname: 'guest1' } ]
[ { msg: 'welcome', nickname: 'guest1' } ]
executed many timews why
executed many timews why
[ { msg: 'welcome', nickname: 'guest1' } ]
[ { msg: 'welcome', nickname: 'guest1' } ]
executed many timews why
[ { msg: 'welcome', nickname: 'guest1' } ]

如何让我的中间件只执行一次?如果我接下来拿走它,它只运行一次但页面不会加载,如果我保持next(),它会执行多次。

1 个答案:

答案 0 :(得分:5)

您的中间件已设置为每个请求都会被调用。这意味着,如果配置不正确的Express,将为您在索引模板中使用的每个图像,样式表或JS文件调用它。

如果这些文件由express.static提供,请确保在 express.static声明之后加载中间件:

app.use(express.static(...));

app.use(...your middleware...);

app.get('/', ...);

这样,您的中间件就不会被调用静态资源,因为express.static会在您的中间件之前处理它们。

您还可以创建单独的中间件功能并将其插入特定路径:

let myMiddleware = function(req, res, next) {
  ...
});

app.get('/', myMiddleware, function(req, res) {
  res.render('index', {})
});