Bird
0
0

Identify the error in this functional middleware code:

medium📝 Debug Q14 of 15
NestJS - Middleware
Identify the error in this functional middleware code:
function auth(req, res, next) {
  if (!req.headers.authorization) {
    res.status(401).send('Unauthorized');
  }
  next();
}
Ares.status should be res.sendStatus
BMissing req parameter in function signature
Cnext() is called even after sending response, causing errors
DAuthorization header check is incorrect
Step-by-Step Solution
Solution:
  1. Step 1: Analyze flow after sending response

    If authorization header is missing, response is sent with 401, but next() is still called, which can cause errors by continuing the request cycle.
  2. Step 2: Identify correct fix

    To fix, add return before res.status(401).send(...) to stop execution or call next() only if authorized.
  3. Final Answer:

    next() is called even after sending response, causing errors -> Option C
  4. Quick Check:

    Call next() only if no response sent [OK]
Quick Trick: Don't call next() after sending response [OK]
Common Mistakes:
  • Calling next() after res.send causes errors
  • Forgetting to stop middleware after response
  • Misusing res.status vs res.sendStatus

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More NestJS Quizzes