0
0
Expressframework~10 mins

Protecting routes with auth middleware 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 import the Express module.

Express
const express = require([1]);
Drag options to blanks, or click blank then click option'
A"express"
B"http"
C"fs"
D"path"
Attempts:
3 left
💡 Hint
Common Mistakes
Using a wrong module name like "http" or "fs".
Forgetting the quotes around the module name.
2fill in blank
medium

Complete the code to create an Express app instance.

Express
const app = [1]();
Drag options to blanks, or click blank then click option'
Arouter
Brequire
Cexpress
Dmiddleware
Attempts:
3 left
💡 Hint
Common Mistakes
Trying to call require() instead of express().
Using undefined variables like router().
3fill in blank
hard

Fix the error in the middleware function to correctly call next.

Express
function authMiddleware(req, res, next) {
  if (req.user) {
    [1]();
  } else {
    res.status(401).send('Unauthorized');
  }
}
Drag options to blanks, or click blank then click option'
Ares.next
Breq.next
Cnext
Dnext()
Attempts:
3 left
💡 Hint
Common Mistakes
Writing next without parentheses.
Trying to call res.next() which does not exist.
4fill in blank
hard

Fill both blanks to protect the route with the auth middleware.

Express
app.[1]('/dashboard', [2], (req, res) => {
  res.send('Welcome to your dashboard');
});
Drag options to blanks, or click blank then click option'
Aget
Bpost
CauthMiddleware
Dexpress.json()
Attempts:
3 left
💡 Hint
Common Mistakes
Using POST instead of GET for a page route.
Using unrelated middleware like express.json() instead of auth middleware.
5fill in blank
hard

Fill all three blanks to create and use auth middleware that checks for a token header.

Express
function [1](req, res, next) {
  const token = req.headers['[2]'];
  if (token === 'secret') {
    next();
  } else {
    res.status(403).send('Forbidden');
  }
}

app.[3]('/protected', [1], (req, res) => {
  res.send('Protected content');
});
Drag options to blanks, or click blank then click option'
AauthMiddleware
Bauthorization
Cget
Dx-access-token
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong header names like 'authorization' when the code expects 'x-access-token'.
Using POST instead of GET for a simple protected page.