Complete the code to apply a middleware globally in a NestJS app.
app.[1](new LoggerMiddleware());In NestJS, to apply middleware globally, you use the app.use() method.
Complete the code to implement a middleware class with the correct method signature.
export class LoggerMiddleware implements NestMiddleware { [1](req: Request, res: Response, next: Function) { console.log('Request logged'); next(); } }
The middleware class must implement a use method to handle requests.
Complete the code to apply the middleware globally in the bootstrap function.
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.[1](new LoggerMiddleware());
await app.listen(3000);
}In NestJS, to apply middleware globally, you use the app.use(new LoggerMiddleware()) method on the app instance.
Fill both blanks to correctly configure global middleware in the main module.
import { MiddlewareConsumer, Module, [1] } from '@nestjs/common'; @Module({}) export class AppModule implements [2] { configure(consumer: MiddlewareConsumer) { consumer.apply(LoggerMiddleware).forRoutes('*'); } }
The module must implement NestModule to configure middleware.
Fill all three blanks to create a middleware that logs request method and URL.
export class LoggerMiddleware implements NestMiddleware { use(req: Request, res: Response, [1]) { console.log(`${req.[2] request to ${req.[3]`); next(); } }
next() causes the request to hang.The middleware method receives next as the third argument. The request method is req.method and the URL is req.url.