Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/37.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何在NestJS中记录所有Axios外部http请求_Javascript_Node.js_Typescript_Axios_Nestjs - Fatal编程技术网

Javascript 如何在NestJS中记录所有Axios外部http请求

Javascript 如何在NestJS中记录所有Axios外部http请求,javascript,node.js,typescript,axios,nestjs,Javascript,Node.js,Typescript,Axios,Nestjs,我希望能够用完整的url、标题等记录每个axios请求,但目前还没有找到这样做的方法 到目前为止,我实现的是基于此编写一个Http拦截器 即req: _dumped:false _events:Object {} _eventsCount:0 _maxListeners:undefined _parsedOriginalUrl:Url {protocol: null, slashes: null, auth: null, …} _parsedUrl:Url {protocol: null, sl

我希望能够用完整的url、标题等记录每个axios请求,但目前还没有找到这样做的方法

到目前为止,我实现的是基于此编写一个Http拦截器

req

_dumped:false
_events:Object {}
_eventsCount:0
_maxListeners:undefined
_parsedOriginalUrl:Url {protocol: null, slashes: null, auth: null, …}
_parsedUrl:Url {protocol: null, slashes: null, auth: null, …}
_readableState:ReadableState {objectMode: false, highWaterMark: 16384, buffer: BufferList, …}
baseUrl:""
body:Object {}
client:Socket {connecting: false, _hadError: false, _handle: TCP, …}
complete:true
connection:Socket {connecting: false, _hadError: false, _handle: TCP, …}
destroyed:false
fresh:false
headers:Object {accept: "application/json, text/plain, */*", user-agent: "axios/0.18.0", host: "localhost:3000", …}
host:"localhost"
hostname:"localhost"
httpVersion:"1.1"
httpVersionMajor:1
httpVersionMinor:1
ip:"::ffff:127.0.0.1"
ips:Array(0)
method:"GET"
next:function next(err) { … }
originalUrl:"/api/data"
params:Object {}
__proto__:Object {constructor: , __defineGetter__: , __defineSetter__: , …}
path:"/api/data"
protocol:"http"
query:Object {}
rawHeaders:Array(8) ["Accept", "application/json, text/plain, */*", "User-Agent", …]
rawTrailers:Array(0) []
readable:true
readableBuffer:BufferList
readableFlowing:null
readableHighWaterMark:16384
readableLength:0
res:ServerResponse {_events: Object, _eventsCount: 1, _maxListeners: undefined, …}
route:Route {path: "/api/data", stack: Array(1), methods: Object}
secure:false
socket:Socket {connecting: false, _hadError: false, _handle: TCP, …}
stale:true
statusCode:null
statusMessage:null
subdomains:Array(0)
trailers:Object {}
upgrade:false
url:"/api/data"
xhr:false

Nest.js-Interceptors只处理控制器处理的请求和发出的响应。如果在处理控制器请求时使用Axios发出http请求,则侦听器不会处理这些请求


Axios拦截器
HttpService
通过
get axiosRef()
直接公开其
axios
实例。使用它,您可以添加:

例如,您可以在
AppModule
中执行此操作


委派给门面 或者,您可以创建一个
HttpService
facade,记录请求并将所有调用委托给内置的
HttpService

@Injectable()
export class MyHttpService {
  private logger: Logger = new Logger(MyHttpService.name);

  constructor (private httpService: HttpService) {}

  public get<T = any>(url: string, config?: AxiosRequestConfig): Observable<AxiosResponse<T>> {
    this.logger.log({url, config});
    return this.httpService.get(url, config)
       .pipe(tap(response => this.logger.log(response)));
  }

  // ... all the other methods you need.

}
@Injectable()
导出类MyHttpService{
专用记录器:记录器=新记录器(MyHttpService.name);
构造函数(私有httpService:httpService){}
公共get(url:string,config?:AxiosRequestConfig):可观察{
this.logger.log({url,config});
返回此.httpService.get(url,配置)
.pipe(点击(响应=>this.logger.log(响应));
}
//…你需要的所有其他方法。
}
您可以创建自己的
LoggingHttpModule
,导入内置的
HttpModule
并导出您的
MyHttpService

npm i @types/morgan

npm i morgan
然后


你会推荐哪种方法?第二种方法似乎需要更多的代码。如果使用
Axios拦截器
方法,将
this.httpService.axiosRef.interceptors.request.use(config=>console.log(config))粘贴到何处代码<代码>>例如,您可以在AppModule的onModuleInit()中执行此操作
-您是否可以提供更多关于此操作的背景信息?请查看此答案的第二部分,其中解释了
onModuleInit
。是的,我建议使用axios拦截器解决方案。在NestJS的typescript版本中,我需要使用稍微修改过的拦截器
this.httpService.axiosRef.interceptors.request.use((config:AxiosRequestConfig)=>{console.log(config);return config;})
@KimKern刚刚对你的答案发表了评论
this.httpService.axiosRef.interceptors.request.use(config => console.log(config));
@Injectable()
export class MyHttpService {
  private logger: Logger = new Logger(MyHttpService.name);

  constructor (private httpService: HttpService) {}

  public get<T = any>(url: string, config?: AxiosRequestConfig): Observable<AxiosResponse<T>> {
    this.logger.log({url, config});
    return this.httpService.get(url, config)
       .pipe(tap(response => this.logger.log(response)));
  }

  // ... all the other methods you need.

}
npm i @types/morgan

npm i morgan
import * as morgan from 'morgan';

export class AppModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer
      .apply(morgan('combined'))
      .forRoutes('*');
  }
}