Utilizing the express library along with the logging library known as morgan
Provided below is a snippet of working code that can be used to reproduce this in nodejs:
const express = require('express')
const morgan = require('morgan')
const app = express()
app.use(express.json()) //middleware
const customFormat = (tokens, req, res) => {
let rarr = [
tokens.method(req, res),
tokens.url(req, res),
tokens.status(req, res),
tokens.res(req, res, 'content-length'), '-',
tokens['response-time'](req, res), 'ms'
]
return rarr.join(' ')
}
app.use(morgan(customFormat))
app.use( (req, res, next) => {
console.log("hello");
next();
});
let data = [
{
"id": 1,
"name": "alpha"
},
{
"id": 2,
"name": "beta",
},
{
"id": 3,
"name": "gamma"
}
]
app.get("/api/persons", (request, response) => {
response.send(data)
})
What could be the reason behind the console output of "hello" appearing before the message logged by the Morgan middleware, considering the order of middleware declaration?
It seems like the Morgan middleware is waiting for the entire request to be completed before logging, could this behavior be related to the internal workings of Morgan?
Various attempts have been made by rearranging the middleware order and using async functions within app.use()