Introduction
NestJS is a progressive Node.js framework that builds a bridge between the simplicity of ExpressJS and an object-oriented, class-based approach. It provides a variety of features to help developers build scalable and maintainable server-side applications, including dependency injection, modularity, and testing support.
One of the most important aspects of any server-side application is its ability to handle HTTP requests. NestJS provides a number of tools and features to make this task easy and efficient.
Using the Http Service
The HttpService is a NestJS dependency that provides a number of methods for making HTTP requests. It is a wrapper around the popular Axios HTTP client library, and it provides a number of advantages over using Axios directly, such as:
- It is automatically injected into controllers, so you don’t have to worry about manually creating and managing instances.
- It provides a number of helper methods for common tasks, such as making GET, POST, PUT, and DELETE requests.
- It transforms the resulting HTTP responses into Observables, which makes it easy to handle asynchronous responses.
To use the HttpService, you first need to import the HttpModule into your NestJS application. Once you have done this, you can inject the HttpService into any controller or service using the @Inject() decorator.
Once you have injected the HttpService, you can use it to make HTTP requests by calling the appropriate method. For example, to make a GET request to the https://example.com/api/users endpoint, you would use the following code:
import { HttpService } from '@nestjs/axios';
constructor(private readonly httpService: HttpService) {}
async findAllUsers(): Promise<User[]> {
const response = await this.httpService.get('https://example.com/api/users');
return response.data;
}
Handling request and response objects
The HttpService methods return Observables, which means that they can emit multiple values over time. In the case of an HTTP request, the Observable will emit a single value, which is the HTTP response object.
The HTTP response object contains a number of properties, including the response status code, headers, and body. You can access these properties using the dot notation. For example, to get the response status code, you would use the following code:
const response = await this.httpService.get('https://example.com/api/users');
const statusCode = response.status;
You can also use the HTTP response object to access the response headers and body. For example, to get the response body, you would use the following code:
const response = await this.httpService.get('https://example.com/api/users');
const users: User[] = response.data;
Handling errors
When making HTTP requests, it is important to handle errors gracefully. You can do this by using the try/catch block or by subscribing to the Observable returned by the HttpService method.
If you use the try/catch block, you can catch any errors that occur and handle them accordingly. For example, the following code shows how to handle a 404 error:
try {
const response = await this.httpService.get('https://example.com/api/users/123');
} catch (error) {
if (error.response.status === 404) {
// Handle 404 error
} else {
// Handle other errors
}
}
If you subscribe to the Observable returned by the HttpService method, you can use the catchError() operator to handle errors. The catchError() operator takes a callback function that is invoked if the Observable emits an error. The callback function can then handle the error accordingly.
For example, the following code shows how to use the catchError() operator to handle a 404 error:
this.httpService.get('https://example.com/api/users/123').subscribe(
(response) => {
// Handle success
},
(error) => {
if (error.response.status === 404) {
// Handle 404 error
} else {
// Handle other errors
}
}
);
Conclusion
Handling HTTP requests in NestJS is easy and efficient. The HttpService provides a number of methods for making HTTP requests, and it transforms the resulting HTTP responses into Observables, which makes it easy to handle asynchronous responses.
For more such posts, please follow our LinkedIn page- FrontEnd Competency.