Step 7

Look at these four lines from index.js file:

app.use(cors());
app.use(helmet());
app.use(express.json());
app.use(noteRoutes);

The pattern of app.use(something) is how Express employs middleware functions.

Middleware functions are functions that have access to the request object (req) and the response object (res), and they can modify application’s request-response cycle.

For example, cors and helmet add "headers" to all our responses before they are actually sent to client. The express.json reads all the requests and if they contain JSON payload, it parses the JSON and makes it available to us through req.body object.

There are many middleware available for Express and you can make your own. The best place to start is "Using middleware" on Express official Guidelines. You can also look at Express middleware under Resources at expressjs.com for a list of popular middleware functions. We have already used a few but let's add another one:

Stop the API server and install morgan

npm install morgan

Next, update the index.js file by

  1. Importing morgan

    const morgan = require("morgan");
    
  2. Linking it to express

    app.use(morgan("dev"));
    

We use morgan to log HTTP requests. As you interact with the API server, you can look at the console (terminal) for the server and see the requests that are received and served by the server. Morgan generated color-coded output based on response status for development use. For example, output will be colored green for success codes, red for server error codes, yellow for client error codes, cyan for redirection codes, etc.

Run the server again and run some of the API requests in Postman. Make note of console as the server is running: