0
0
Node.jsframework~10 mins

Middleware concept and execution flow in Node.js - Interactive Code Practice

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

Complete the code to define a middleware function that logs the request method.

Node.js
function logger(req, res, [1]) {
  console.log(req.method);
  next();
}
Drag options to blanks, or click blank then click option'
Ahandler
Bcallback
Cnext
Ddone
Attempts:
3 left
💡 Hint
Common Mistakes
Using incorrect parameter names like 'callback' or 'done' instead of 'next'.
2fill in blank
medium

Complete the code to use the middleware in an Express app.

Node.js
const express = require('express');
const app = express();

app.use([1]);

app.listen(3000);
Drag options to blanks, or click blank then click option'
Alogger
Blogger()
Clogger.call()
Dlogger.apply()
Attempts:
3 left
💡 Hint
Common Mistakes
Calling the middleware function immediately by adding parentheses.
3fill in blank
hard

Fix the error in the middleware to ensure it passes control correctly.

Node.js
function checkAuth(req, res, [1]) {
  if (!req.user) {
    res.status(401).send('Unauthorized');
  } else {
    next();
  }
  // Missing call to continue middleware chain
}
Drag options to blanks, or click blank then click option'
Acontinue
Bdone
Ccallback
Dnext
Attempts:
3 left
💡 Hint
Common Mistakes
Not calling next() causing the request to hang.
4fill in blank
hard

Fill both blanks to create middleware that modifies the request and passes control.

Node.js
function addRequestTime(req, res, [1]) {
  req.requestTime = Date.now();
  [2]();
}
Drag options to blanks, or click blank then click option'
Anext
Bres.send
Cnext()
Dreq.next
Attempts:
3 left
💡 Hint
Common Mistakes
Calling res.send instead of next().
5fill in blank
hard

Fill all three blanks to create middleware that checks a header and either continues or sends an error.

Node.js
function checkHeader(req, res, [1]) {
  if (req.headers['x-api-key'] === '[2]') {
    [3]();
  } else {
    res.status(403).send('Forbidden');
  }
}
Drag options to blanks, or click blank then click option'
Anext
B12345
Cnext()
Dcallback
Attempts:
3 left
💡 Hint
Common Mistakes
Not calling next() or using wrong parameter names.