Search code examples
typescriptaxiosnestjs

Nest.js RangeError: Maximum call stack size exceeded


I want to make a request to to an external api using axios and nestjs.

I took this answer Nestjs using axios and instead of execute the request in the controller I created a service

// controller
import { Controller, Get } from '@nestjs/common';
import { CollectService } from './collect.service';


@Controller('collect')
export class CollectController {
    constructor(private collectService: CollectService) {}


    @Get()
    getResponse(){
         this.getResponse();

    }
   

}

// ----------service ------------------------

import { Injectable, HttpService } from '@nestjs/common';

@Injectable()
export class CollectService {

    constructor(private httpService: HttpService) {}


    async getResponse() {
       
        const response = await this.httpService.get('https://reqres.in/api/users/2').toPromise();
        return response.data;

    
     
        }
      
}


which gave me a stackoverflow


[Nest] 23928   - 02/28/2021, 12:16:18 PM   [ExceptionsHandler] Maximum call stack size exceeded +74479ms
RangeError: Maximum call stack size exceeded

what caused this behavior ?


Solution

  • You call controller's getResponse() infinity, then it throws Maximum call stack size exceeded error.

    I think you want to call the service's function instead:

        @Get()
        getResponse(){
             this.collectService.getResponse();
    
        }