Quick Index
Plan


We'll make a small improvement to our app by adding a middleware function.

We'll start off by simply logging a message in the middleware.

These steps will are similar to the previous example's steps.

Example Steps


Example Directory Structure 💡
This is the directory structure used in this example.

We need to be meticulous about matching directory structures because the program will use it to locate files.
express-1c
  controllers
    home-controller.js
    middleware.js
  package.json
  main.js
Create Project Directory
Create a project directory named "express-1c"
/express-1c
Add Project Sub-Directory
Within the project root dir, add a sub-dir named "controllers"
/express-1c/controllers
Initialize Project
Initialize the project normally.

🐞 gotcha - be sure to run this command from the project root dir (not a sub-dir).
>npm init
Install Packages
Use the npm install command to install the public packages http-status-codes and express

Note we install two packages here (we could also do this by running two commands).
>npm install http-status-codes express
Controller Code
Now we'll code the home controller.

  • Go to "controllers" sub-dir
  • Create "home-controller.js"
  • Copy provided code into file
  • Save

Note that we are just moving "homeFct" out of "main" and into the controller file.
const
	codes = require('http-status-codes'),
	br = '<br>';
	
const homeFct = (req, res) => {
	res.type('html')
	res.status(codes.OK);
	res.write('Greetings from web app' + br);
	res.write('Hello from controller');
	res.end();
};

exports.homeFct = homeFct;
Middleware Code
Now we'll code a middleware piece.

  • Go to "controllers" sub-dir
  • Create "middleware.js"
  • Copy provided code into file
  • Save

NOTE WELL -- this handler receives an additional param "nextFct", and we call that function at the end of our work.
//middleware.js

const middlewareFct = (req, res, nextFct) => {
	console.log('request received in middleware');
	console.log(`url path and query: ${req.url}`);
	//Run param "nextFct" (and end this function)
	nextFct();
};

exports.middlewareFct = middlewareFct;
Main Code
In the project root dir, create main.js using the example code.

We make two changes to our previous (example) main.js file:

  • Import the middleware module
  • Tell the web "app" to use it
"use strict";

const
	port = 3000,
	express = require("express"),
	hc = require('./controllers/home-controller'),
	middleware = require('
1
./controllers/middleware'), app = express(), msg = `Server started on port: ${port}`; const started = () => console.log(msg); //use middleware
2
app.use(middleware.middlewareFct); //route path "/" to controller's "homeFct" app.get("/", hc.homeFct); //start the web server app app.listen(port, started);
Run
Start the web server

Note: you very likely can setup a shortcut in your IDE to run the current file
>node main
Open Browser on URL
  • Open a web browser.
  • Go to the address bar
  • Enter "http://localhost:3000/" in the address bar or click the provided link
  • Browse the console for the middleware logging


http://localhost:3000/

console output:
Server started on port: 3000
request received in middleware
url path and query: /


Hint -- middleware output is in console (not browser)
The End
We are now familiar with how to setup and use middleware. We only logged messages but as our project grows the middleware can take on a significant role.












Navigation