Complete the code to define a middleware function that logs the request method.
function logger(req, res, [1]) {
console.log(req.method);
next();
}The third parameter in Express middleware is always called next. It is a function that passes control to the next middleware.
Complete the code to use the custom middleware in an Express app.
const express = require('express'); const app = express(); app.use([1]); app.get('/', (req, res) => res.send('Hello')); app.listen(3000);
To use a middleware, you pass its function name to app.use(). Here, logger is the middleware function.
Fix the error in the middleware to correctly handle asynchronous operations.
async function auth(req, res, [1]) { const user = await getUser(req.headers.token); if (!user) { return res.status(401).send('Unauthorized'); } next(); }
The middleware must call next to pass control. The parameter must be named next to be called correctly.
Fill both blanks to create middleware that adds a timestamp to the request and calls next.
function addTimestamp(req, res, [1]) { req.[2] = Date.now(); next(); }
The third parameter must be next to continue the middleware chain. The timestamp is stored in req.timestamp.
Fill all three blanks to create middleware that checks if user is admin and calls next or sends 403.
function checkAdmin(req, res, [1]) { if (req.user && req.user.role === [2]) { [3]; } else { res.status(403).send('Forbidden'); } }
The middleware uses next as the third parameter. It checks if req.user.role equals 'admin'. If yes, it calls next() to continue.