0
0
NestJSframework~10 mins

Applying middleware to routes in NestJS - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete 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'
Aattach
Buse
CapplyToRoutes
DforRoutes
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'use' instead of 'forRoutes' causes a syntax error.
Trying to call 'applyToRoutes' which does not exist.
2fill in blank
medium

Complete 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'
Ausers
Bproducts
Corders
Dauth
Attempts:
3 left
💡 Hint
Common Mistakes
Using a wrong route path string causes middleware not to apply.
Forgetting to import RequestMethod when specifying method.
3fill in blank
hard

Fix 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'
A'orders'
B['orders', 'products']
C{ path: 'orders', method: RequestMethod.POST }
DRequestMethod.POST
Attempts:
3 left
💡 Hint
Common Mistakes
Passing an array of strings instead of route objects causes errors.
Passing only method without path is invalid.
4fill in blank
hard

Fill 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'
ARequestMethod.POST
BRequestMethod.GET
CRequestMethod.PUT
DRequestMethod.DELETE
Attempts:
3 left
💡 Hint
Common Mistakes
Using GET or DELETE instead of POST or PUT.
Passing strings instead of RequestMethod enum values.
5fill in blank
hard

Fill 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'
ARequestMethod.GET
BRequestMethod.POST
CRequestMethod.DELETE
DRequestMethod.PUT
Attempts:
3 left
💡 Hint
Common Mistakes
Using PUT instead of DELETE.
Passing strings instead of RequestMethod enum values.