Home » Node.js

Node.js and Morgan Middleware

In this tutorial, we are going to learn about an important middleware (also a module) named Morgan.
Submitted by Godwill Tetah, on June 23, 2019

Hi! In this article, we'll be talking about another very important aid in coding with node. It's a middleware (also a module) called Morgan.

Like said earlier, Node modules are like libraries which help us perform specific tasks. Node.js is always considered powerful because it has a very large ecosystem of third-party modules.

Morgan is used to output request details on the console. Therefore, Morgan output's anything that happens on the webpage.

This function is very important for developers to help them understand every operation they perform during building or testing and application.

Take Note! You should have Node.js installed in your PC.

With Node.js already up and running, let's get started.

First of all, install the Morgan module by typing npm install morgan on the command line or npm install morgan –save

Morgan middleware in Node.js

Wait for a while as it downloads.

NB: Internet required!

To see how this awesome Morgan middleware works? Let's create an express file server.

Open a text editor and type the following code and save it with the file name app.js:

const express = require('express');
const http = require('http');
const morgan = require('morgan') // include morgan module

const hostname = 'localhost';
const port = 8080;

const app = express();
// use morgan to log request details

// index file to be served directory
app.use(express.static(__dirname + '/my web page')); 
app.use((req, res, next) => {
    res.statusCode = 200; // status code
    res.setHeader('content-type', 'text/html');
    // default response if file to be served not found.
    res.end('<html><body><h1>This is an express Server</h1></body></html>') 
const server = http.createServer(app);
server.listen(port, hostname, () => {
    console.log(`server running at http://${hostname}:${port}`)


The file should be saved in your default node.js project directory.

Initiate the JavaScript file at the console by typing node app.js

Take Note!: Your command line directory should be same with node js module/project directory.

Open your browser and navigate to http://localhost:8080

Morgan middleware in Node.js

Finally, open the command line console again to see the details from Morgan

Morgan middleware in Node.js

From the output above you can see the time and file requested details from Morgan.

Thanks for coding with me. Your comments are most welcome.

Comments and Discussions!

Load comments ↻

Copyright © 2024 www.includehelp.com. All rights reserved.