0
0
Node.jsframework~10 mins

Middleware vs decorator pattern in Node.js - Interactive Practice

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

Complete the code to create a simple middleware function in Express that logs request method and URL.

Node.js
function logger(req, res, next) {
  console.log(req.[1] + ' ' + req.url);
  next();
}
Drag options to blanks, or click blank then click option'
Apath
Burl
Cbody
Dmethod
Attempts:
3 left
💡 Hint
Common Mistakes
Using req.url instead of req.method for the HTTP method
Trying to access req.path which is not the method
Logging req.body which is the request data, not the method
2fill in blank
medium

Complete the code to apply a decorator function that adds a greeting to the original function's output.

Node.js
function greet() {
  return 'World';
}

function decorator(fn) {
  return function() {
    return 'Hello ' + fn[1]();
  };
}
Drag options to blanks, or click blank then click option'
Acall
Bapply
C()
D.call
Attempts:
3 left
💡 Hint
Common Mistakes
Using fn.call without parentheses, which is a function reference, not a call
Using fn.apply which requires arguments array
Using .call as a string which is invalid syntax
3fill in blank
hard

Fix the error in the middleware function to correctly handle asynchronous operations.

Node.js
async function auth(req, res, [1]) {
  const user = await getUser(req.token);
  if (!user) {
    res.status(401).send('Unauthorized');
  } else {
    next();
  }
}
Drag options to blanks, or click blank then click option'
Anext
Bcallback
Cdone
Dproceed
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different name like done or callback which Express does not recognize
Not calling next() at all causing the request to hang
4fill in blank
hard

Fill both blanks to create a decorator that logs before and after calling the original function.

Node.js
function logDecorator(fn) {
  return function(...args) {
    console.[1]('Before call');
    const result = fn(...args);
    console.[2]('After call');
    return result;
  };
}
Drag options to blanks, or click blank then click option'
Alog
Bwarn
Cerror
Dinfo
Attempts:
3 left
💡 Hint
Common Mistakes
Using console.warn or console.error which are for warnings or errors
Mixing different console methods in the two blanks
5fill in blank
hard

Fill all three blanks to create middleware that checks for a token and calls next or sends error.

Node.js
function checkToken(req, res, [1]) {
  const token = req.headers['[2]'];
  if (!token) {
    res.status([3]).send('Token missing');
  } else {
    next();
  }
}
Drag options to blanks, or click blank then click option'
Anext
Bauthorization
C401
Dtoken
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong header name like 'token' instead of 'authorization'
Using wrong status code like 403 instead of 401
Naming the third argument incorrectly