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的不同

相关推荐
Bellafu6661 小时前
selenium 常用xpath写法
前端·selenium·测试工具
blackorbird3 小时前
Edge 浏览器 IE 模式成攻击突破口:黑客借仿冒网站诱导攻击
前端·edge
谷歌开发者4 小时前
Web 开发指向标 | Chrome 开发者工具学习资源 (一)
前端·chrome·学习
名字越长技术越强4 小时前
Chrome和IE获取本机ip地址
前端
天***88964 小时前
Chrome 安装失败且提示“无可用的更新” 或 “与服务器的连接意外终止”,Chrome 离线版下载安装教程
前端·chrome
半梦半醒*4 小时前
zabbix安装
linux·运维·前端·网络·zabbix
大怪v5 小时前
【搞发🌸活】不信书上那套理论!亲测Javascript能卡浏览器Reader一辈子~
javascript·html·浏览器
清羽_ls5 小时前
React Hooks 核心规则&自定义 Hooks
前端·react.js·hooks
你的人类朋友5 小时前
“签名”这个概念是非对称加密独有的吗?
前端·后端·安全
西陵5 小时前
Nx带来极致的前端开发体验——任务缓存
前端·javascript·架构