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

相关推荐
m0_7482382734 分钟前
项目升级Sass版本或升级Element Plus版本遇到的问题
前端·rust·sass
升讯威在线客服系统1 小时前
如何通过 Docker 在没有域名的情况下快速上线客服系统
java·运维·前端·python·docker·容器·.net
AsBefore麦小兜1 小时前
Vite vs Webpack
前端·webpack
LaughingZhu1 小时前
PH热榜 | 2025-02-23
前端·人工智能·经验分享·搜索引擎·产品运营
道不尽世间的沧桑3 小时前
第17篇:网络请求与Axios集成
开发语言·前端·javascript
diemeng11194 小时前
AI前端开发技能变革时代:效率与创新的新范式
前端·人工智能
bin91536 小时前
DeepSeek 助力 Vue 开发:打造丝滑的复制到剪贴板(Copy to Clipboard)
前端·javascript·vue.js·ecmascript·deepseek
晴空万里藏片云8 小时前
elment Table多级表头固定列后,合计行错位显示问题解决
前端·javascript·vue.js
曦月合一8 小时前
html中iframe标签 隐藏滚动条
前端·html·iframe
奶球不是球8 小时前
el-button按钮的loading状态设置
前端·javascript