Complete the code to define a middleware function that logs the request method.
async function logger(ctx, next) {
console.log(ctx.request.[1]);
await next();
}The method property of ctx.request gives the HTTP method like GET or POST.
Complete the code to call the next middleware in the chain.
async function auth(ctx, next) {
if (!ctx.request.headers.get('Authorization')) {
ctx.response.status = 401;
return;
}
await [1]();
}The next function is passed to middleware and must be awaited to continue the chain.
Fix the error in the middleware that sets a custom header.
async function customHeader(ctx, next) {
await next();
ctx.response.headers.[1]('X-Custom', 'Hello');
}The headers object has a set method to add or update headers.
Fill both blanks to create a middleware that measures response time.
async function responseTime(ctx, [1]) { const start = Date.now(); await [2](); const ms = Date.now() - start; ctx.response.headers.set('X-Response-Time', `${ms}ms`); }
The second parameter is usually named next and must be awaited to continue middleware chain.
Fill all three blanks to create a middleware that catches errors and sets status 500.
async function errorHandler(ctx, [1]) { try { await [2](); } catch ([3]) { ctx.response.status = 500; ctx.response.body = 'Internal Server Error'; } }
The second parameter is next to call next middleware. The catch block uses error to capture the exception.
