codecamp

NestJS HTTP模块

Axios 是一个功能丰富的 HTTP 客户端包,被广泛使用。 Nest 封装了 Axios 并通过内置的 HttpModule 将其公开。 HttpModule 导出 HttpService 类,该类公开基于 Axios 的方法来执行 HTTP 请求。 该库还将生成的 HTTP 响应转换为 Observables。

我们还可以直接使用任何通用的 Node.js HTTP 客户端库,包括 got 或 undici。

安装

要开始使用它,我们首先安装所需的依赖项。

$ npm i --save @nestjs/axios

开始使用

安装过程完成后,要使用 HttpService,首先导入 HttpModule。

@Module({
  imports: [HttpModule],
  providers: [CatsService],
})
export class CatsModule {}

接下来,使用普通的构造函数注入来注入 HttpService。

HttpModule 和 HttpService 是从 @nestjs/axios 包中导入的。
@Injectable()
export class CatsService {
  constructor(private httpService: HttpService) {}

  findAll(): Observable<AxiosResponse<Cat[]>> {
    return this.httpService.get('http://localhost:3000/cats');
  }
}
axiosResponse 是从 axios 包中导出的接口($ npm i axios)。

所有 HttpService 方法都返回一个包装在 Observable 对象中的 AxiosResponse。

配置

Axios 可以配置多种选项来自定义 HttpService 的行为。 要配置底层 Axios 实例,请在导入时将可选选项对象传递给 HttpModule 的 register() 方法。 这个选项对象将直接传递给底层的 Axios 构造函数。

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

异步配置

当我们需要异步而不是静态地传递模块选项时,请使用 registerAsync() 方法。 与大多数动态模块一样,Nest 提供了几种处理异步配置的技术。

一种技术是使用工厂函数:

HttpModule.registerAsync({
  useFactory: () => ({
    timeout: 5000,
    maxRedirects: 5,
  }),
});

和其他工厂提供者一样,我们的工厂函数可以是异步的,可以通过 inject 注入依赖。

HttpModule.registerAsync({
  imports: [ConfigModule],
  useFactory: async (configService: ConfigService) => ({
    timeout: configService.get('HTTP_TIMEOUT'),
    maxRedirects: configService.get('HTTP_MAX_REDIRECTS'),
  }),
  inject: [ConfigService],
});

或者,我们可以使用类而不是工厂来配置 HttpModule,如下所示。

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

上面的构造在 HttpModule 中实例化了 HttpConfigService,使用它来创建一个选项对象。 请注意,在此示例中,HttpConfigService 必须实现 HttpModuleOptionsFactory 接口,如下所示。 HttpModule 将调用所提供类的实例化对象上的 createHttpOptions() 方法。

@Injectable()
class HttpConfigService implements HttpModuleOptionsFactory {
  createHttpOptions(): HttpModuleOptions {
    return {
      timeout: 5000,
      maxRedirects: 5,
    };
  }
}

如果要重用现有选项提供程序而不是在 HttpModule 中创建私有副本,请使用 useExisting 语法。

HttpModule.registerAsync({
  imports: [ConfigModule],
  useExisting: HttpConfigService,
});


NestJS 流式处理文件
NestJS Session(会话)
温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定
目录

关闭

MIP.setData({ 'pageTheme' : getCookie('pageTheme') || {'day':true, 'night':false}, 'pageFontSize' : getCookie('pageFontSize') || 20 }); MIP.watch('pageTheme', function(newValue){ setCookie('pageTheme', JSON.stringify(newValue)) }); MIP.watch('pageFontSize', function(newValue){ setCookie('pageFontSize', newValue) }); function setCookie(name, value){ var days = 1; var exp = new Date(); exp.setTime(exp.getTime() + days*24*60*60*1000); document.cookie = name + '=' + value + ';expires=' + exp.toUTCString(); } function getCookie(name){ var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)'); return document.cookie.match(reg) ? JSON.parse(document.cookie.match(reg)[2]) : null; }