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', { })
})
When I visit '/' once, console prints the following:
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' } ]
How can I make my middleware to execute only once? If I take away next, it runs only once but page won't load, and if I keep next(), it executes many times.
Your middleware is set up to get called for each request. This means that with an incorrectly configured Express, it will get called for each image-, stylesheet- or JS-file that you happen to be using in your index template.
If those files are served by express.static
, make sure that your middleware gets loaded after the express.static
declaration:
app.use(express.static(...));
app.use(...your middleware...);
app.get('/', ...);
This way, your middleware won't be called for the static resources because express.static
will handle them before your middleware.
You can also create a separate middleware function and insert it into specific routes:
let myMiddleware = function(req, res, next) {
...
});
app.get('/', myMiddleware, function(req, res) {
res.render('index', {})
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With