0
0
Node.jsframework~10 mins

Building custom middleware 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'
Anext
Bdone
Ccallback
Dhandle
Attempts:
3 left
💡 Hint
Common Mistakes
Using a wrong parameter name like 'done' or 'callback' instead of 'next'.
Forgetting to call the next function.
2fill in blank
medium

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

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

app.use([1]);

app.get('/', (req, res) => res.send('Hello'));

app.listen(3000);
Drag options to blanks, or click blank then click option'
Aexpress
Blogger
Capp
Dnext
Attempts:
3 left
💡 Hint
Common Mistakes
Passing the wrong variable like 'express' or 'app' instead of the middleware function.
Forgetting to pass the middleware function to app.use.
3fill in blank
hard

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

Node.js
async function auth(req, res, [1]) {
  const user = await getUser(req.headers.token);
  if (!user) {
    return res.status(401).send('Unauthorized');
  }
  next();
}
Drag options to blanks, or click blank then click option'
Ahandle
Bdone
Ccallback
Dnext
Attempts:
3 left
💡 Hint
Common Mistakes
Using a wrong parameter name for the next function.
Not calling next() after async checks.
4fill in blank
hard

Fill both blanks to create middleware that adds a timestamp to the request and calls next.

Node.js
function addTimestamp(req, res, [1]) {
  req.[2] = Date.now();
  next();
}
Drag options to blanks, or click blank then click option'
Anext
Btimestamp
Ctime
Ddate
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong parameter names for next.
Storing timestamp in a wrong property name.
5fill in blank
hard

Fill all three blanks to create middleware that checks if user is admin and calls next or sends 403.

Node.js
function checkAdmin(req, res, [1]) {
  if (req.user && req.user.role === [2]) {
    [3];
  } else {
    res.status(403).send('Forbidden');
  }
}
Drag options to blanks, or click blank then click option'
Anext
B'admin'
Cnext()
D'user'
Attempts:
3 left
💡 Hint
Common Mistakes
Not calling next() as a function.
Checking for wrong role string.
Using wrong parameter name for next.