0
0
NestJSframework~30 mins

Status codes and headers in NestJS - Mini Project: Build & Apply

Choose your learning style9 modes available
Status codes and headers
📖 Scenario: You are building a simple NestJS API that responds to client requests with proper HTTP status codes and custom headers. This helps clients understand the result of their requests and receive extra information.
🎯 Goal: Create a NestJS controller with one GET endpoint that returns a JSON message. Set a custom HTTP status code and add a custom header to the response.
📋 What You'll Learn
Create a controller named AppController
Add a GET route handler method named getHello
Set the HTTP status code to 201 (Created) for the response
Add a custom header X-Custom-Header with value NestJS
Return a JSON object with a message property set to 'Hello World'
💡 Why This Matters
🌍 Real World
APIs often need to send specific status codes and headers to inform clients about the result of their requests and provide extra metadata.
💼 Career
Understanding how to control HTTP status codes and headers is essential for backend developers building RESTful APIs with NestJS.
Progress0 / 4 steps
1
Create the controller and GET method
Create a NestJS controller class named AppController. Inside it, add a method named getHello decorated with @Get() that returns an object { message: 'Hello World' }.
NestJS
Need a hint?

Use @Controller() to define the controller and @Get() to define the GET route handler.

2
Add HTTP status code 201
Import @HttpCode from @nestjs/common. Add the decorator @HttpCode(201) above the getHello method to set the HTTP status code to 201.
NestJS
Need a hint?

The @HttpCode() decorator sets the response status code.

3
Inject response object to set headers
Import Res and Response from @nestjs/common and express respectively. Modify the getHello method to accept a parameter res decorated with @Res() and typed as Response. Use res.setHeader('X-Custom-Header', 'NestJS') to add the custom header. Then send the JSON response using res.status(201).json({ message: 'Hello World' }).
NestJS
Need a hint?

Use the @Res() decorator to get the response object and set headers before sending the response.

4
Complete the controller with proper imports
Ensure the imports include Controller, Get, HttpCode, and Res from @nestjs/common, and Response from express. The AppController class should have the getHello method as defined with the custom header and status code.
NestJS
Need a hint?

Check that all imports and method code are correct and complete.