NestJS Basic 2 — Questions and Answers
Question 1: Which decorator is used to define a NestJS controller?
- @Injectable()
- @Controller() (Correct answer)
- @Module()
- @Service()
Correct answer: @Controller()
@Controller() marks a class as a NestJS controller that handles incoming HTTP requests.
Question 2: What does the @Get() decorator do in NestJS?
- Injects a dependency
- Defines a GET HTTP route handler (Correct answer)
- Retrieves a module
- Fetches configuration values
Correct answer: Defines a GET HTTP route handler
@Get() maps an HTTP GET request to a specific controller method.
Question 3: Which file is the entry point of a NestJS application?
- app.module.ts
- app.controller.ts
- main.ts (Correct answer)
- app.service.ts
Correct answer: main.ts
main.ts bootstraps the NestJS application using NestFactory.create().
Question 4: What is the purpose of the @Injectable() decorator in NestJS?
- Marks a class as a controller
- Marks a class as a NestJS module
- Marks a class as a provider that can be injected (Correct answer)
- Marks a class as a middleware
Correct answer: Marks a class as a provider that can be injected
@Injectable() marks a class as a provider so NestJS's IoC container can manage and inject it.
Question 5: How do you extract a route parameter from a URL like /users/:id in NestJS?
- @Query('id')
- @Body('id')
- @Param('id') (Correct answer)
- @Header('id')
Correct answer: @Param('id')
@Param('id') extracts named route parameters from the URL path.
Question 6: What does NestFactory.create() return?
- A plain Express app
- An INestApplication instance (Correct answer)
- A module reference
- A router object
Correct answer: An INestApplication instance
NestFactory.create() returns an INestApplication instance used to configure and start the app.
Question 7: Which of the following is a valid way to define a POST route in NestJS?
- @Post() on a controller method (Correct answer)
- @HttpPost() on a service method
- @Route('POST') on a module
- @Method('post') on a provider
Correct answer: @Post() on a controller method
@Post() is the correct HTTP method decorator placed on a controller method to handle POST requests.
Which decorator is used to define a NestJS controller?