Complete the code to call the next middleware function in Express.
app.use((req, res, [1]) => { console.log('Middleware 1'); [1](); });
In Express, the next function is used to pass control to the next middleware.
Complete the code to skip to the next middleware when a condition is met.
app.use((req, res, next) => {
if (req.user) {
[1]();
} else {
res.status(401).send('Unauthorized');
}
});Calling next() passes control to the next middleware if the user exists.
Fix the error in the middleware to properly handle errors and pass them to the error handler.
app.use((req, res, next) => {
try {
throw new Error('Something went wrong');
} catch (err) {
[1](err);
}
});Passing the error to next(err) tells Express to skip normal middleware and go to error handlers.
Fill both blanks to create middleware that logs the request and then passes control to the next middleware.
app.use(([1], [2], next) => { console.log(`Request URL: $[1].url`); next(); });
The first two parameters are req and res by convention in Express middleware.
Fill all three blanks to create error-handling middleware that logs the error and sends a 500 response.
app.use(([1], [2], [3], next) => { console.error([1].message); [3].status(500).send('Server Error'); });
Error-handling middleware has four parameters: err, req, res, and next. Here, err is used to log the error, res to send the response, and req is the request object.