What is the method by which Morgan middleware consistently displays the output on the console following the execution of all other middleware

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()

Answer №1

By default, Morgan is set up to execute after the response is complete in order to log the time it took. However, if you check out the code on GitHub, you have the option to change this behavior using the immediate property.

app.use(morgan(customFormat, {
    immediate: true
}))

Here is the snippet of code from the morgan source:

if (immediate) {
  // immediate log
  logRequest()
} else {
  // record response start
  onHeaders(res, recordStartTime)

  // log when response finished
  onFinished(res, logRequest)
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Are you looking for outcomes related to Bootstrap typeahead feature?

I am facing an issue with returning results for the bootstrap typeahead after making an ajax request. Strangely, it works fine without initiating the ajax request. The code that doesn't work: $(".typeahead").typeahead({ source: function(query, pr ...

Heroku experiencing technical difficulties while local version is running smoothly

Despite my node.js and express application running smoothly on the local host, I encounter an Application Error after successfully deploying it to Heroku. Unfortunately, the app fails to run on Heroku. Inspecting the heroku logs with --tail reveals the fo ...

Code is not running in ReactJS

My challenge is to use canvas and script to draw a rectangle with one diagonal line. However, when I try to do so, only the rectangle appears on my browser. It seems like the script is not being executed. Here's the code: import React, { Component } ...

Tips for incorporating API-provided CSS values into AngularJS expressions for stylish card customization

I am in the process of creating unique Pokemon cards that pull data from an API. My question is, how can I apply specific CSS styling to each card directly from the API, similar to how I have utilized AngularJS to render the information? So far, I have su ...

What is the process of invoking an external JavaScript function in Angular 5?

I recently downloaded a theme from this source. I need to specify script and CSS in the index.html file. The body section of index.html looks like this: <body> <app-root></app-root> <script type="text/javascript" src="./assets/js ...

Tips for modifying the class of a span inline element using a javascript function

Looking for assistance in creating a password text box with an eye icon that toggles visibility. When the user clicks on the eye icon, it should change to a crossed-out eye icon and switch the input type to text. <div class="input-group show-hide-passw ...

How to make L.divIcon stand out on Leaflet map with mouse hover or through programming

Is there a way to highlight the L.divIcon svg markers on mouseover or trigger it from another action, such as clicking a button? An example test case can be found here: https://jsfiddle.net/sxvLykkt/5/ The markers are dynamically generated (originally ge ...

Is it possible to remove content from a Content Editable container?

JSFiddle <div contenteditable="true"> <p>Trying out editing capabilities of this paragraph.</p> <figure> <img src="http://www.keenthemes.com/preview/metronic/theme/assets/global/plugins/jcrop/demos/demo_files/ima ...

Is there a way to identify the moment when a dynamically added element has finished loading?

Edit: I've included Handlebar template loading in my code now. I've been attempting to identify when an element that has been dynamically added (from a handlebars template) finishes loading, but unfortunately, the event doesn't seem to trig ...

While making a promise, an error occurred: TypeError - Unable to access the property '0' of null

I encountered an issue when trying to assign data from a function. The error appears in the console ((in promise) TypeError: Cannot read property '0'), but the data still shows on my application. Here is the code: <template> ...

A guide on dynamically altering text upon hovering over an element using Vue.js

On my website, I have the following HTML code: <div class="greetings"> <img @mouseover="hover='A'" @mouseleave="hover=''" src="a.png" alt="A" /> <img @mouseover="hover='B'" @mouseleave="hover=''" ...

An error occurred stating "No matching closing tag found for "<%" when attempting to include the file

While attempting to include other .ejs files using the same syntax, everything works perfectly except when including my _show.ejs file. I am unsure where the issue lies, whether it is in the index.ejs or _show.ejs file. This is my index.ejs File <!-- i ...

Is jQuery capable of appropriately escaping my quotes?

Currently, I am utilizing $.cookie() to retrieve all the values from a cookie which are stored in JSON format: var properties = $.cookie('params'); The output of properties is: {"distinct_id": "13f97d6600b42e-000e6293c-6b1b2e75-232800-13f97d66 ...

Issues with Ajax functionality in Rails

I believe my lack of knowledge in Ajax might be the reason for this issue. My goal is to continuously make ajax calls to my server as I am creating a demo app for learning purposes. Below is the code snippet: Code from job_status/index.html.erb file &l ...

The PHP blocking code in Zend Server not only blocks the response of the current ajax call but also impacts the handling

I encountered a peculiar problem. Suppose I have an ajax call like this; $.ajax({ url:"url1.php", }) Following this ajax call, I have another ajax call as follows; $.ajax({ url:"url2.php", success:function(data){console.log(data);} }) ...

express-subdomain not recognizing any subdomains

I have been struggling to use express-subdomain to differentiate between example.com and subdomain.example.com in my local environment, but unfortunately, I am consistently getting the output assigned to example.com. Despite trying different syntaxes based ...

Tips for retrieving the slug value in getStaticProps for invoking the API with the slug as a parameter

Content on the Page: import { useRouter } from "next/router"; export default function Daily({ data }) { let router = useRouter() const { slug } = router.query; return slug; } And display on the page 60d6180ea9284106a4fd8441 ...

Tips for generating multiple HTML hyperlinks using a for loop in a Chrome extension

function createDropDown(){ const tree = document.createDocumentFragment(); const link = document.createElement('a'); for(let index = 0; index < urlList.length; index++){ link.appendChild(document.createTextNode(urlList[index])); ...

Attempting to forward an image in a node-js/express application

I am facing an issue with a broken image link when trying to access it through Express: app.get('/fileThumbnail', function(req, res) { var url = proxiedURL +"?" + querystring.stringify(req.query); logger.info('/fileThumbnail going to url& ...

The jQuery Deferred feature on Ajax is failing to properly pass the array in the data option as an array, instead converting

I am facing an issue in my application where I want to use jQuery deferred to handle Ajax success and error uniformly from a central location. It works perfectly fine when I pass strings in the data option, but when I try to pass an array, it gets sent as ...