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
Middleware can be generic to all paths, or triggered only on specific path(s) your server handles. Below is an example of middleware declaration.
Ref: https://medium.com/@agoiabeladeyemi/a-simple-explanation-of-express-middleware-c68ea839f498
Answer mentioned in the comment by @AikonMogwai is also correct: