如何添加用于记录传出请求的拦截器?我知道我可以将它添加到HttpService的每个实例,如下所示:
this.httpService.axiosRef.interceptors.request.use((config) => ...)
但是我只想添加一次,这就是为什么我要问是否有一种在模块级别添加它的方法--我看到了一个向模块添加配置的选项,如下所示:
imports: [HttpModule.register({...})]
有人知道如何以这种方式配置拦截器?提前谢谢。
发布于 2022-06-08 10:03:50
作为一个变体,您可以使用这个示例编写您自己的HttpModule,这将使用Axios HttpSerive。要使用 register \ registerAsync ,您需要从Axios HttpModule (在示例 AxiosHttpModule 上)对模块进行 extends
register
registerAsync
AxiosHttpModule
extends
import { HttpModule as AxiosHttpModule, HttpService } from '@nestjs/axios'; import { Global, Inject, Module, OnModuleInit } from '@nestjs/common'; import { WINSTON_MODULE_NEST_PROVIDER } from 'nest-winston'; import { Logger } from '@app/common/Logger'; import { createReqInterceptor, createRespFailInterceptor, createRespSuccessInterceptor, } from '@app/common/http/http.interceptors'; @Global() @Module({ imports: [AxiosHttpModule], exports: [AxiosHttpModule], export class HttpModule extends AxiosHttpModule implements OnModuleInit { constructor( private readonly httpService: HttpService, @Inject(WINSTON_MODULE_NEST_PROVIDER) private readonly logger: Logger, super(); public onModuleInit(): any { const axios = this.httpService.axiosRef; axios.interceptors.request.use(function (config: AxiosRequestConfig) { //... some logic axios.interceptors.response.use( function (response: AxiosResponse) { //... some logic function (err: AxiosError) { //... some logic