How to use the Node.js axios library for making HTTP requests with interceptors for logging in Nest.js



Image not found!!

Using Axios with interceptors for logging in a Nest.js application involves creating a custom interceptor to log HTTP requests and responses. Here's how you can achieve this:

  1. Install Axios:

    If you haven't already installed Axios, you can do so using npm or yarn:

    npm install axios

    or

    csharp
    yarn add axios
  2. Create a LoggingInterceptor:

    In Nest.js, interceptors are used to intercept and manipulate requests and responses. Create a custom interceptor to log HTTP requests and responses.

    typescript
    // logging.interceptor.ts import { Injectable, NestInterceptor, ExecutionContext, CallHandler, Logger } from '@nestjs/common'; import { Observable } from 'rxjs'; import { tap } from 'rxjs/operators'; import axios, { AxiosRequestConfig, AxiosResponse } from 'axios'; @Injectable() export class LoggingInterceptor implements NestInterceptor { private readonly logger = new Logger(LoggingInterceptor.name); intercept(context: ExecutionContext, next: CallHandler): Observable<any> { const request = context.switchToHttp().getRequest(); const method = request.method; const url = request.url; const start = Date.now(); return next.handle().pipe( tap((response: AxiosResponse) => { const statusCode = response.status; const elapsedTime = Date.now() - start; this.logger.log(`${method} ${url} ${statusCode} ${elapsedTime}ms`); }), // Error handling catchError((error: AxiosError) => { const statusCode = error.response ? error.response.status : 'Request failed'; const elapsedTime = Date.now() - start; this.logger.error(`${method} ${url} ${statusCode} ${elapsedTime}ms`); throw error; }) ); } }
  3. Register the LoggingInterceptor:

    Register the LoggingInterceptor in your Nest.js module to apply it to HTTP requests.

    typescript
    // app.module.ts import { Module } from '@nestjs/common'; import { APP_INTERCEPTOR } from '@nestjs/core'; import { LoggingInterceptor } from './logging.interceptor'; @Module({ providers: [ { provide: APP_INTERCEPTOR, useClass: LoggingInterceptor, }, ], }) export class AppModule {}
  4. Use Axios for HTTP Requests:

    You can now use Axios for making HTTP requests within your Nest.js services or controllers. The interceptor will log the details of each request and its response.

    typescript
    import { Injectable } from '@nestjs/common'; import axios from 'axios'; @Injectable() export class ApiService { async fetchData(): Promise<any> { try { const response = await axios.get('https://api.example.com/data'); return response.data; } catch (error) { throw error; // Let Nest.js handle error responses } } }

With this setup, Axios will automatically log each HTTP request and its response. Adjust the interceptor's logic according to your specific logging requirements.