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

相关推荐
熊猫钓鱼>_>2 分钟前
基于MCP的桥梁设计规范智能解析与校审系统构建实践
前端·easyui·设计规范
qq_346295272 分钟前
require/exports 或 import/export的联系和区别,各自的使用场景
javascript
flying robot5 分钟前
小结:JavaScript 模块化工具链
javascript
若初&13 分钟前
文件上传Ⅲ
前端·web安全
若愚679213 分钟前
前端取经路——前端安全:构建坚不可摧的Web应用防线
前端·安全
邪恶的贝利亚17 分钟前
定时器设计
java·linux·前端
inksci37 分钟前
Vue 3 打开 el-dialog 时使 el-input 获取焦点
前端·javascript·vue.js
若愚67921 小时前
前端取经路——量子UI:响应式交互新范式
前端·ui·交互
PHASELESS4111 小时前
HTML常用标签用法全解析:构建语义化网页的核心指南
前端·html