Rapid distribution of 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', { })
})
When I find "/" once, the 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 only do middleware once? If I take it further, it only runs once, but the page won't load, and if I keep next (), it runs many times.
source to share
Your middleware is set up to call for every request. This means that if Express is not configured correctly, it will be called for every image, style, or JS file that you use in your index template.
If these files are being served express.static
, make sure your middleware is loaded after the announcement express.static
:
app.use(express.static(...));
app.use(...your middleware...);
app.get('/', ...);
This way, your middleware will not be called on static resources because it express.static
will handle them before your middleware.
You can also create a separate intermediate function and insert it into specific routes:
let myMiddleware = function(req, res, next) {
...
});
app.get('/', myMiddleware, function(req, res) {
res.render('index', {})
});
source to share