Axios is a useful tool for sending requests to websites or web services using JavaScript. In Nest.js, Axios sends requests to external APIs or other online services. The Axios module for Nest.js acts as a bridge between Nest.js and Axios, making it easier to use Axios in our Nest.js applications. This module provides a service compatible with Nest.js, allowing us to send HTTP requests within our application.
To use Axios in our Nest.js application, we need to install it first using npm
or yarn
:
npm install axios @nestjs/axios # npm installationyarn add axios @nestjs/axios # yarn installation
After installation, we need to import the HttpModule
from @nestjs/axios
in our module:
import { Module } from '@nestjs/common';import { HttpModule } from '@nestjs/axios';import { AppController } from './app.controller';@Module({imports: [HttpModule],controllers: [AppController],})export class AppModule {}
Now we can inject the HttpService
provided by the HttpModule
in our controller or service. Explore the code in the widget below and click the "Run" button to see the response:
import { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; async function bootstrap() { const app = await NestFactory.create(AppModule); await app.listen(3000); } bootstrap();
Let's see the code explanation for the main files of the demo application below:
app.service.ts
fileLine 1: We import the HttpService
class from the @nestjs/axios
module.
Lines 5–21: We define a new class AppService
decorated with the @Injectable
decorator.
Line 7: We define a constructor that injects an instance of the HttpService
class into the service.
Lines 9–20: We define a new method getPosts()
and it returns the API response.
Lines 10–11: We use the HttpService
instance injected into the service to make a GET
request to the URL https://jsonplaceholder.typicode.com/posts/1
.
Line 13: We return the data property of the response object, which contains the response body from the API we called.
app.controller.ts
fileLines 1–2: We import the Controller
and Get
decorators from the @nestjs/common
module and the AppService
class we created before.
Lines 4–13: We define a new class AppController
decorated with the @Controller('/api')
decorator.
Line 6: We define a constructor that injects an instance of the AppService
class into the controller.
Lines 8–12: We define a new route handler getBlogPosts()
for the GET
HTTP method using the @Get('/posts')
decorator, which returns the result of calling the getPosts()
method.
Overall, this code defines a new controller for our Nest.js application that provides a route handler for the GET
HTTP method. The route handler uses the AppService
class, which uses HttpService
, to make a GET request to an external API and return the response body.
Note: The
@Post()
,@Put()
, and@Delete()
decorators are used in defining a route handler for the HTTPPOST
,PUT
, andDELETE
methods, respectively.
Free Resources