node.jsexpressmean-stackmeanjs

Why content of middleware is running four times on single request from browser


Why does console.log('First Log') run 4 times per request?

//app.js
const express = require('express');
var app = express();

app.use((req, res, next) => {
  console.log('First Log'); // problem is here
  next();
});

app.use((req, res, next) => {
  res.send('first response from express');
});

module.exports = app;
//server.js
const http = require('http');
const app  = require('./backend/app');

var port =  process.env.PORT || 3000;

app.set('port', port);

var server = http.createServer(app);
server.listen(port);

Output:

First Log
First Log
First Log
First Log

Solution

  • Middleware can be generic to all paths, or triggered only on specific path(s) your server handles. Below is an example of middleware declaration.

    var app = express();
    app.use(function () {}) //added to all paths or globally
    app.get('/someroute', function() {}) //added to a specific path
    

    Ref: https://medium.com/@agoiabeladeyemi/a-simple-explanation-of-express-middleware-c68ea839f498

    Answer mentioned in the comment by @AikonMogwai is also correct:

    The middleware works one time for each url(of the same route path): index.html, favicon.ico, *.css, etc. 
    Change console.log to console.log(req.url) to see that.