HTTP module

Axios is richly featured HTTP client package that is widely used. Nest wraps Axios and exposes it via the built-in HttpModule. The HttpModule exports the HttpService class, which exposes Axios-based methods to perform HTTP requests. The library also transforms the resulting HTTP responses into Observables.

info Hint You can also use any general purpose Node.js HTTP client library directly, including got or undici.

Installation

To begin using it, we first install the required dependency.

  1. $ npm i --save @nestjs/axios

Getting started

Once the installation process is complete, to use the HttpService, first import HttpModule.

  1. @Module({
  2. imports: [HttpModule],
  3. providers: [CatsService],
  4. })
  5. export class CatsModule {}

Next, inject HttpService using normal constructor injection.

info Hint HttpModule and HttpService are imported from @nestjs/axios package.

  1. @@filename()
  2. @Injectable()
  3. export class CatsService {
  4. constructor(private httpService: HttpService) {}
  5. findAll(): Observable<AxiosResponse<Cat[]>> {
  6. return this.httpService.get('http://localhost:3000/cats');
  7. }
  8. }
  9. @@switch
  10. @Injectable()
  11. @Dependencies(HttpService)
  12. export class CatsService {
  13. constructor(httpService) {
  14. this.httpService = httpService;
  15. }
  16. findAll() {
  17. return this.httpService.get('http://localhost:3000/cats');
  18. }
  19. }

info Hint AxiosResponse is an interface exported from the axios package ($ npm i axios).

All HttpService methods return an AxiosResponse wrapped in an Observable object.

Configuration

Axios can be configured with a variety of options to customize the behavior of the HttpService. Read more about them here. To configure the underlying Axios instance, pass an optional options object to the register() method of HttpModule when importing it. This options object will be passed directly to the underlying Axios constructor.

  1. @Module({
  2. imports: [
  3. HttpModule.register({
  4. timeout: 5000,
  5. maxRedirects: 5,
  6. }),
  7. ],
  8. providers: [CatsService],
  9. })
  10. export class CatsModule {}

Async configuration

When you need to pass module options asynchronously instead of statically, use the registerAsync() method. As with most dynamic modules, Nest provides several techniques to deal with async configuration.

One technique is to use a factory function:

  1. HttpModule.registerAsync({
  2. useFactory: () => ({
  3. timeout: 5000,
  4. maxRedirects: 5,
  5. }),
  6. });

Like other factory providers, our factory function can be async and can inject dependencies through inject.

  1. HttpModule.registerAsync({
  2. imports: [ConfigModule],
  3. useFactory: async (configService: ConfigService) => ({
  4. timeout: configService.getString('HTTP_TIMEOUT'),
  5. maxRedirects: configService.getString('HTTP_MAX_REDIRECTS'),
  6. }),
  7. inject: [ConfigService],
  8. });

Alternatively, you can configure the HttpModule using a class instead of a factory, as shown below.

  1. HttpModule.registerAsync({
  2. useClass: HttpConfigService,
  3. });

The construction above instantiates HttpConfigService inside HttpModule, using it to create an options object. Note that in this example, the HttpConfigService has to implement HttpModuleOptionsFactory interface as shown below. The HttpModule will call the createHttpOptions() method on the instantiated object of the supplied class.

  1. @Injectable()
  2. class HttpConfigService implements HttpModuleOptionsFactory {
  3. createHttpOptions(): HttpModuleOptions {
  4. return {
  5. timeout: 5000,
  6. maxRedirects: 5,
  7. };
  8. }
  9. }

If you want to reuse an existing options provider instead of creating a private copy inside the HttpModule, use the useExisting syntax.

  1. HttpModule.registerAsync({
  2. imports: [ConfigModule],
  3. useExisting: ConfigService,
  4. });