0
0
Expressframework~10 mins

Middleware factory pattern in Express - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to create a middleware factory that returns a middleware function.

Express
function logger(level) {
  return function(req, res, next) {
    console.log(level + ': Request received');
    [1]();
  };
}
Drag options to blanks, or click blank then click option'
Ares
Bnext
Creq
Dconsole
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting to call next() causes the request to hang.
2fill in blank
medium

Complete the code to use the middleware factory with a specific log level.

Express
const express = require('express');
const app = express();

app.use(logger([1]));
Drag options to blanks, or click blank then click option'
A'info'
Binfo
Clevel
Dconsole
Attempts:
3 left
💡 Hint
Common Mistakes
Passing an undefined variable instead of a string.
3fill in blank
hard

Fix the error in the middleware factory to correctly handle the next function.

Express
function logger(level) {
  return function(req, res, next) {
    console.log(level + ': Request received');
    [1];
  };
}
Drag options to blanks, or click blank then click option'
Anext
Bnext.call
Cnext.call()
Dnext()
Attempts:
3 left
💡 Hint
Common Mistakes
Writing next without parentheses, causing the middleware to not proceed.
4fill in blank
hard

Fill both blanks to create a middleware factory that logs the method and URL of requests.

Express
function requestLogger([1]) {
  return function(req, res, [2]) {
    console.log(req.method + ' ' + req.url);
    next();
  };
}
Drag options to blanks, or click blank then click option'
Alevel
Bnext
Cres
Drequest
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong parameter names or forgetting to call next().
5fill in blank
hard

Fill all three blanks to create a middleware factory that adds a custom header with the given name and value.

Express
function headerSetter([1], [2]) {
  return function(req, res, [3]) {
    res.setHeader([1], [2]);
    next();
  };
}
Drag options to blanks, or click blank then click option'
AheaderName
BheaderValue
Cnext
Dres
Attempts:
3 left
💡 Hint
Common Mistakes
Mixing parameter names or forgetting to call next().