Complete the code to create a simple middleware function in Express that logs request method and URL.
function logger(req, res, next) {
console.log(req.[1] + ' ' + req.url);
next();
}The req.method property contains the HTTP method of the request, such as GET or POST. This is what we want to log along with the URL.
Complete the code to apply a decorator function that adds a greeting to the original function's output.
function greet() {
return 'World';
}
function decorator(fn) {
return function() {
return 'Hello ' + fn[1]();
};
}To call the function fn inside the decorator, we use fn(). The parentheses () invoke the function.
Fix the error in the middleware function to correctly handle asynchronous operations.
async function auth(req, res, [1]) { const user = await getUser(req.token); if (!user) { res.status(401).send('Unauthorized'); } else { next(); } }
In Express middleware, the third argument is always named next. It is a function to call to pass control to the next middleware.
Fill both blanks to create a decorator that logs before and after calling the original function.
function logDecorator(fn) {
return function(...args) {
console.[1]('Before call');
const result = fn(...args);
console.[2]('After call');
return result;
};
}The console.log method is used to print normal messages to the console. We want to log both before and after the function call.
Fill all three blanks to create middleware that checks for a token and calls next or sends error.
function checkToken(req, res, [1]) { const token = req.headers['[2]']; if (!token) { res.status([3]).send('Token missing'); } else { next(); } }
The third middleware argument is next. The token is usually in the authorization header. The status code for missing token is 401 Unauthorized.