Controllers in NestJS
Welcome to Controllers in NestJS
Welcome back! So far, we've covered how to set up your first NestJS application and understand its basic structure. Now, it's time to delve deeper into the backbone of your application — the controllers. In this lesson, you'll learn what controllers are, how to create them, and why they're essential in a NestJS environment.
What Are Controllers?
A controller in NestJS is responsible for handling incoming HTTP requests and returning a response to the client. Controllers are a crucial part of developing server-side applications as they define how different endpoints respond to client requests. They act as the entry point to your application's functionality, coordinating between the client requests and the business logic encapsulated in services.
Controllers are typically used to manage routing, meaning they determine which function to call when a specific URL is requested by a client. By structuring your application with controllers, you ensure that your code is modular, testable, and easy to maintain.
Routing
Let's take a look at how routing works by exploring an example with the CorgiController.
First, we define a new controller by creating a file named corgi.controller.ts:
The @Controller('corgi') decorator defines a controller class in NestJS. It tells NestJS that this particular class will handle routes that start with /corgi. Within this controller, you can define various methods that correspond to different endpoints.
For example, in the CorgiController, we use the @Get() decorator to indicate that the showCorgis() method should handle GET requests for the /corgi route. This means that when someone navigates to /corgi, this method will be called.
To render a view in response to this GET request, we use the @Render('index') decorator. This tells NestJS to use the index.hbs template file to generate the HTML that will be sent back to the client. The showCorgis() method itself returns an object containing a message, which is then passed to the template for rendering. The message is displayed dynamically in the view, providing the final output to the user.
