简体   繁体   English

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

[英]How to log all Axios external http requests in NestJS

I want to be able to log each axios request with full url, headers, etc but currently didn't find a way to do so. 我希望能够使用完整的URL,标头等记录每个axios请求,但目前没有找到这样的方法。

What I did achieve so far is to writhe an Http Interceptor based on this answer 到目前为止,我确实实现了基于此答案的Http拦截器

export class HttpLoggerInterceptor implements NestInterceptor {
  intercept(
    context: ExecutionContext,
    call$: Observable<any>,
  ): Observable<any> {
    return call$.pipe(
      map(data => {
        // pipe call to add / modify header(s) after remote method
        const req = context.switchToHttp().getRequest();
        return data;
      }),
    );
  }
}

Now I browse through the objects req and context props on debug but could not see Asios request url, etc. Unless I missed that. 现在,我在调试时浏览了对象reqcontext道具,但是看不到Asios请求url等。除非我错过了。

My controller route ( api/data in that case) have N number of http external calls taking place but interceptor intercepts only controller controller call not Axios calls. 我的控制器路由(在这种情况下为api/data )进行了N次HTTP外部调用,但拦截器仅拦截了控制器控制器调用,而不拦截Axios调用。

Any thoughts? 有什么想法吗?

That is context object: 那是context对象:

args:Array(2) [IncomingMessage, ServerResponse]
constructorRef:class AppController { … }
getRequest:() => …
getResponse:() => …
handler:data() { … }
__proto__:Object {constructor: , getClass: , getHandler: , …}

that is req : 那是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 only process the request handled by your controller and the response going out. Nest.js-Interceptors仅处理由您的控制器处理的请求和响应。 If you make http requests with Axios while you handle a controller request, they won't be processed by an interceptor. 如果您在处理控制器请求时使用Axios发出http请求,则拦截器将不会处理它们。


Axios Interceptor Axios拦截器

The HttpService exposes its axios instance directly via get axiosRef() . HttpService通过get axiosRef()直接公开其axios实例。 With it, you can add an axios interceptor : 有了它,您可以添加axios interceptor

this.httpService.axiosRef.interceptors.request.use(config => console.log(config));

You can for example do that in the onModuleInit() of your AppModule . 例如,您可以在onModuleInit()AppModule


Delegate to Facade 委托给立面

As an alternative, you can create an HttpService facade, that logs the request and delegates all calls to the built-in HttpService : 另外,您可以创建一个HttpService门面,记录请求并将所有调用委托给内置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.

}

You can create your own LoggingHttpModule that imports the built-in HttpModule and exports your MyHttpService . 您可以创建自己的LoggingHttpModule ,以导入内置的HttpModule并导出MyHttpService

npm i @types/morgan

npm i morgan

then 然后

import * as morgan from 'morgan';

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM