HTTP module

Axios is rich-feature HTTP client that is widely used in dozens of applications. That's why Nest wraps this package and exposes it by default as a built-in HttpModule. The HttpModule exports HttpService that simply exposes axios-based methods to perform HTTP request, but also, transforms return types into Observables.

In order to use a HttpService, we need to import HttpModule.

TypeScript

@Module({
  imports: [HttpModule],
  providers: [CatsService],
})
export class CatsModule {}
Hint The HttpModule is exposed from @nestjs/common package.

Then, you can inject HttpService. This class is easily accessible from @nestjs/common package.

JS TS
TypeScript

@Injectable()
export class CatsService {
  constructor(private readonly httpService: HttpService) {}

  findAll(): Observable<AxiosResponse<Cat[]>> {
    return this.httpService.get('http://localhost:3000/cats');
  }
}
TypeScript

@Injectable()
@Dependencies(HttpService)
export class CatsService {
  constructor(httpService) {
    this.httpService = httpService;
  }

  findAll() {
    return this.httpService.get('http://localhost:3000/cats');
  }
}

All methods return AxiosResponse wrapped with Observable object.

Configuration

Axios gives a bunch of options that you may take advantage of to make your HttpService even more powerful. Read more about them here. To configure underlying library instance, use register() method of HttpModule.

TypeScript

@Module({
  imports: [HttpModule.register({
    timeout: 5000,
    maxRedirects: 5,
  })],
  providers: [CatsService],
})
export class CatsModule {}

All these properties will be passed down to the axios constructor.

  • HTTP module
  • Configuration

Support us

Nest is an MIT-licensed open source project. It can grow thanks to the support by these awesome people. If you'd like to join them, please read more here.

Principal Sponsor

Sponsors / Backers