0
0
Expressframework~10 mins

Conditional middleware execution 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 add middleware that runs only for POST requests.

Express
app.use((req, res, next) => {
  if (req.method === '[1]') {
    console.log('POST request detected');
  }
  next();
});
Drag options to blanks, or click blank then click option'
AGET
BDELETE
CPUT
DPOST
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'GET' instead of 'POST' will run middleware on GET requests.
Forgetting to call next() will block the request.
2fill in blank
medium

Complete the code to apply middleware only on routes starting with '/admin'.

Express
app.use('[1]', (req, res, next) => {
  console.log('Admin route accessed');
  next();
});
Drag options to blanks, or click blank then click option'
A/user
B/api
C/admin
D/public
Attempts:
3 left
💡 Hint
Common Mistakes
Using '/user' will not affect admin routes.
Leaving the path empty applies middleware to all routes.
3fill in blank
hard

Fix the error in the middleware to run only if query parameter 'debug' equals 'true'.

Express
app.use((req, res, next) => {
  if (req.query.debug [1] 'true') {
    console.log('Debug mode active');
  }
  next();
});
Drag options to blanks, or click blank then click option'
A===
B==
C=
D!=
Attempts:
3 left
💡 Hint
Common Mistakes
Using '=' causes assignment error.
Using '==' may cause type coercion issues.
4fill in blank
hard

Fill both blanks to create middleware that runs only for PUT requests on '/update' path.

Express
app.[1]('/update', (req, res, next) => {
  if (req.method === '[2]') {
    console.log('Update request received');
  }
  next();
});
Drag options to blanks, or click blank then click option'
Aput
Bpost
CGET
DPUT
Attempts:
3 left
💡 Hint
Common Mistakes
Using app.post() will not handle PUT requests.
Checking req.method === 'GET' will never be true for PUT requests.
5fill in blank
hard

Fill all three blanks to create middleware that runs only if the user is authenticated and the request method is DELETE on '/remove' path.

Express
app.[1]('/remove', (req, res, next) => {
  if (req.user && req.method === '[2]') {
    console.log('Authenticated DELETE request');
    [3]();
  } else {
    res.status(403).send('Forbidden');
  }
});
Drag options to blanks, or click blank then click option'
Adelete
BDELETE
Cnext
Dpost
Attempts:
3 left
💡 Hint
Common Mistakes
Using app.post() instead of app.delete().
Not calling next() causes request to hang.
Checking req.method === 'delete' (lowercase) fails.