NestJS16-HTTP module

Axios有丰富的特性的HTTP服务端包并被广泛的运用。Nest包装了Axios并且通过内置HttpModule导出。HttpModule导出了HttpService类,它基于Axios方法来处理HTTP请求。这个库也转换HTTP返回结果成Observables

提示:您也可以使用任何Node.jsHTTP服务端库,包括got或者undici

安装

首先我们要安装依赖

bash 复制代码
$ npm i --save @nestjs/axios axios

开始

一旦安装进程完成了,为了使用HttpService,首先要导入HttpModule

ts 复制代码
@Module({
  imports: [HttpModule],
  providers: [CatsService],
})
export class CatsModule {}

接着,使用通常的构造器注入HttpService

提示 HttpModuleHttpService是通过@nestjs/axios包导入的

ts 复制代码
@Injectable()
export class CatsService {
  constructor(private readonly httpService: HttpService) {}

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

提示 AxiosResponse是一个接口从axios包($ npm i axios)导入。

所有HttpService方法返回AxiosResponse都被包装成Observable对象。

配置

Axios可以通过这个参数来配置,用于自定义HttpService的行为。在这里阅读更多。为了配置基本Axios实例,当导入它的时候,提供可选参数对象给HttpModuleregister()方法。这个可选的对象会直接传递给Axios构造器。

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

异步配置

当您需要将您的模块参数通过异步配置,使用registerAsync()方法。大多数动态模块,Nest提供几个技术来处理异步配置。

一个技术是使用工厂函数

ts 复制代码
HttpModule.registerAsync({
  useFactory: () => ({
    timeout: 5000,
    maxRedirects: 5,
  }),
});

像其他的工厂provider,我们的工厂函数可以异步并可以通过inject注入依赖。

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

或者,您们可以使用类来代替工厂配置HttpModule,如下。

ts 复制代码
HttpModule.registerAsync({
  useClass: HttpConfigService,
});

HttpModule内部构造器实例化了HttpConfigService,使用它来创建一个参数对象。在例子中,HttpConfigService实现了HttpModuleOptionsFactory接口如下。HttpModule将会在类的实例化对象上调用createHttpOptions()方法。

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

如果在HttpModule中您想入复用存在的参数来代替自己新建的复制版本,使用useExisting语句。

ts 复制代码
HttpModule.registerAsync({
  imports: [ConfigModule],
  useExisting: HttpConfigService,
});

直接使用Axios

如果您觉得HttpModule.register的参数不能满足您,或者您就想直接访问@nestjs/axios创建的基础的Axios实例,您能够通过HttpService#axiosRef来访问它:

ts 复制代码
import { catchError, firstValueFrom } from 'rxjs';

@Injectable()
export class CatsService {
  private readonly logger = new Logger(CatsService.name);
  constructor(private readonly httpService: HttpService) {}

  async findAll(): Promise<Cat[]> {
    const { data } = await firstValueFrom(
      this.httpService.get<Cat[]>('http://localhost:3000/cats').pipe(
        catchError((error: AxiosError) => {
          this.logger.error(error.response.data);
          throw 'An error happened!';
        }),
      ),
    );
    return data;
  }
}

提示 阅读RxJS的文档来查看firstValueFromlastValueFrom的不同

相关推荐
OEC小胖胖4 小时前
去中心化身份:2025年Web3身份验证系统开发实践
前端·web3·去中心化·区块链
Cacciatore->5 小时前
Electron 快速上手
javascript·arcgis·electron
vvilkim5 小时前
Electron 进程间通信(IPC)深度优化指南
前端·javascript·electron
某公司摸鱼前端6 小时前
ES13(ES2022)新特性整理
javascript·ecmascript·es13
ai小鬼头7 小时前
百度秒搭发布:无代码编程如何让普通人轻松打造AI应用?
前端·后端·github
漂流瓶jz7 小时前
清除浮动/避开margin折叠:前端CSS中BFC的特点与限制
前端·css·面试
前端 贾公子7 小时前
在移动端使用 Tailwind CSS (uniapp)
前端·uni-app
散步去海边7 小时前
Cursor 进阶使用教程
前端·ai编程·cursor
清幽竹客7 小时前
vue-30(理解 Nuxt.js 目录结构)
前端·javascript·vue.js
weiweiweb8887 小时前
cesium加载Draco几何压缩数据
前端·javascript·vue.js