Complete the code to create a functional middleware that logs the request method.
export function loggerMiddleware(req, res, next) {
console.log(req.[1]);
next();
}The method property of the request object contains the HTTP method (GET, POST, etc.). Logging it shows which type of request was made.
Complete the code to apply the functional middleware globally in a NestJS app.
import { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; import { loggerMiddleware } from './logger.middleware'; async function bootstrap() { const app = await NestFactory.create(AppModule); app.[1](loggerMiddleware); await app.listen(3000); } bootstrap();
The use method is used to apply functional middleware globally in NestJS.
Fix the error in the functional middleware to correctly handle asynchronous operations.
export async function asyncLoggerMiddleware(req, res, [1]) { await new Promise(resolve => setTimeout(resolve, 100)); console.log('Async log:', req.method); next(); }
The third parameter in middleware functions is conventionally called next. Calling next() continues the request cycle.
Fill both blanks to create a functional middleware that adds a custom header and calls next.
export function customHeaderMiddleware(req, res, [1]) { res.setHeader('[2]', 'NestJS'); next(); }
The third parameter is next to continue the middleware chain. The header X-Custom-Header is a common custom header name.
Fill all three blanks to create a functional middleware that logs the URL, sets a header, and calls next.
export function fullMiddleware(req, res, [1]) { console.log('URL:', req.[2]); res.setHeader('[3]', 'Active'); next(); }
The third parameter is next. The request URL is in req.url. The custom header X-Status is set to indicate status.