0
0
Expressframework~10 mins

next() function and flow control 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 call the next middleware function in Express.

Express
app.use((req, res, [1]) => {
  console.log('Middleware 1');
  [1]();
});
Drag options to blanks, or click blank then click option'
Aend
Bsend
Cnext
Dlisten
Attempts:
3 left
💡 Hint
Common Mistakes
Using res.send() instead of next() to continue middleware.
Forgetting to call next() causing the request to hang.
2fill in blank
medium

Complete the code to skip to the next middleware when a condition is met.

Express
app.use((req, res, next) => {
  if (req.user) {
    [1]();
  } else {
    res.status(401).send('Unauthorized');
  }
});
Drag options to blanks, or click blank then click option'
Ares.redirect
Bnext
Cres.end
Dres.send
Attempts:
3 left
💡 Hint
Common Mistakes
Sending a response and then calling next(), which causes errors.
Not calling next() and blocking the request.
3fill in blank
hard

Fix the error in the middleware to properly handle errors and pass them to the error handler.

Express
app.use((req, res, next) => {
  try {
    throw new Error('Something went wrong');
  } catch (err) {
    [1](err);
  }
});
Drag options to blanks, or click blank then click option'
Anext
Bconsole.log
Cres.status
Dres.send
Attempts:
3 left
💡 Hint
Common Mistakes
Logging the error but not passing it to next(), so error handlers are not triggered.
Sending a response inside catch and then calling next(), causing headers errors.
4fill in blank
hard

Fill both blanks to create middleware that logs the request and then passes control to the next middleware.

Express
app.use(([1], [2], next) => {
  console.log(`Request URL: $[1].url`);
  next();
});
Drag options to blanks, or click blank then click option'
Areq
Bres
Crequest
Dresponse
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong parameter names that don't match Express conventions.
Forgetting to call next() to continue the middleware chain.
5fill in blank
hard

Fill all three blanks to create error-handling middleware that logs the error and sends a 500 response.

Express
app.use(([1], [2], [3], next) => {
  console.error([1].message);
  [3].status(500).send('Server Error');
});
Drag options to blanks, or click blank then click option'
Aerr
Bres
Creq
Dnext
Attempts:
3 left
💡 Hint
Common Mistakes
Mixing up the order of parameters in error middleware.
Not sending a response after logging the error.