Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to apply middleware to all routes in a NestJS module.
NestJS
import { MiddlewareConsumer, Module, NestModule } from '@nestjs/common'; import { LoggerMiddleware } from './logger.middleware'; @Module({}) export class AppModule implements NestModule { configure(consumer: MiddlewareConsumer) { consumer.apply(LoggerMiddleware).[1]('*'); } }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'use' instead of 'forRoutes' causes a syntax error.
Trying to call 'applyToRoutes' which does not exist.
✗ Incorrect
In NestJS, to apply middleware to routes, you use the 'forRoutes' method on the MiddlewareConsumer.
2fill in blank
mediumComplete the code to apply middleware only to the 'users' route.
NestJS
consumer.apply(LoggerMiddleware).forRoutes({ path: '[1]', method: RequestMethod.ALL }); Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a wrong route path string causes middleware not to apply.
Forgetting to import RequestMethod when specifying method.
✗ Incorrect
To apply middleware to a specific route, specify the route path string in the 'forRoutes' method.
3fill in blank
hardFix the error in the code to apply middleware to multiple routes.
NestJS
consumer.apply(LoggerMiddleware).forRoutes({ path: 'users', method: RequestMethod.GET }, [1]); Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Passing an array of strings instead of route objects causes errors.
Passing only method without path is invalid.
✗ Incorrect
To apply middleware to multiple routes, pass multiple route objects to 'forRoutes'.
4fill in blank
hardFill both blanks to apply middleware only to POST and PUT methods on 'products' route.
NestJS
consumer.apply(LoggerMiddleware).forRoutes({ path: 'products', method: [1] }, { path: 'products', method: [2] }); Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using GET or DELETE instead of POST or PUT.
Passing strings instead of RequestMethod enum values.
✗ Incorrect
To target POST and PUT methods, use RequestMethod.POST and RequestMethod.PUT respectively.
5fill in blank
hardFill all three blanks to apply middleware to 'auth' route for GET, POST, and DELETE methods.
NestJS
consumer.apply(AuthMiddleware).forRoutes(
{ path: 'auth', method: [1] },
{ path: 'auth', method: [2] },
{ path: 'auth', method: [3] }
); Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using PUT instead of DELETE.
Passing strings instead of RequestMethod enum values.
✗ Incorrect
Middleware can be applied to multiple HTTP methods by passing route objects with different methods.