Complete the code to create a simple Express middleware function that logs the request method.
function logger(req, res, [1]) {
console.log(req.method);
next();
}The middleware function must include next as the third parameter to pass control to the next middleware.
Complete the code to test an Express middleware that adds a property to the request object.
const req = {};
const res = {};
const next = () => {};
middleware(req, res, [1]);
console.log(req.customProperty);When testing middleware, you call it with req, res, and a next function to simulate Express behavior.
Fix the error in the test code that checks if middleware calls next with an error.
middleware(req, res, (err) => {
if (err) {
console.log('Error handled');
}
[1];
});Using return here stops further execution after handling the error, which is correct in this test callback.
Fill both blanks to create a test that verifies middleware modifies the response and calls next.
const res = {
statusCode: 200,
[1]: function(code) {
this.statusCode = code;
return this;
}
};
middleware(req, res, [2]);send instead of status for setting status code.next.The res.status method sets the status code and returns res for chaining. The next function is passed to middleware to continue processing.
Fill all three blanks to test middleware that conditionally skips to next middleware.
function testMiddleware(req, res, [1]) { if (!req.user) { [2](); return; } res.message = 'User found'; [3](); }
The middleware uses next to skip or continue. The first and second blanks are the next function parameter and call. The third blank is also a call to next to continue processing.