62

I am a nest.js beginner and I am trying to implement Axios with my code and this error occurs and I would like to fix it.

    --> starting at object with constructor 'ClientRequest'
    |     property 'socket' -> object with constructor 'Socket'
    --- property '_httpMessage' closes the circle +188941ms
TypeError: Converting circular structure to JSON
    --> starting at object with constructor 'ClientRequest'
    |     property 'socket' -> object with constructor 'Socket'
    --- property '_httpMessage' closes the circle
    at JSON.stringify (<anonymous>)
    at stringify (D:\CUSportcomplex-register\sso-reg\node_modules\express\lib\response.js:1123:12)
    at ServerResponse.json (D:\CUSportcomplex-register\sso-reg\node_modules\express\lib\response.js:260:14)
    at ExpressAdapter.reply (D:\CUSportcomplex-register\sso-reg\node_modules\@nestjs\platform-express\adapters\express-adapter.js:24:57)
    at RouterResponseController.apply (D:\CUSportcomplex-register\sso-reg\node_modules\@nestjs\core\router\router-response-controller.js:13:36)
    at D:\CUSportcomplex-register\sso-reg\node_modules\@nestjs\core\router\router-execution-context.js:173:48
    at processTicksAndRejections (internal/process/task_queues.js:93:5)
    at async D:\CUSportcomplex-register\sso-reg\node_modules\@nestjs\core\router\router-execution-context.js:47:13
    at async D:\CUSportcomplex-register\sso-reg\node_modules\@nestjs\core\router\router-proxy.js:9:17

This is my app.service.ts

async validateSSO(appticket): Promise<SsoContent> {
        let instance = axios.create({
            baseURL: "http://localhost:8080/",
            headers: {
                'DeeAppId': config.DeeAppId,
                'DeeAppSecret': config.DeeAppSecret,
                'DeeTicket': appticket
            }
        });
        instance.get("/serviceValidation")
            .then(response => {
                this.ssoContent = response;
            })
            .catch(error => {
                return (error);
            });

        return this.ssoContent;

    }

and this is my app.controller.ts

    @Get('validation/:appticket')
    async validateSSO(
        @Param('appticket') appticket: string
        //DeeAppTicket is sented via Front-end
    ): Promise<SsoContent> {
        return this.registeringService.validateSSO(appticket);
    }

Thank you for your help :)

ChuChuwi
  • 719
  • 1
  • 8
  • 13

10 Answers10

43

First of all nest.js provides you HttpService out of the box that you may inject it through DI: https://docs.nestjs.com/techniques/http-module

Second - you are trying to store whole response object which is complex data structure and contains circular dependencies as it stated in error message (TypeError: Converting circular structure to JSON)

What you should do is either you map the data you need instead of storing whole circular object,

or you should look up to some libs that could parse circular json: https://www.npmjs.com/package/flatted

LuckyLuke
  • 1,028
  • 2
  • 14
  • 28
15

Rather than storing the whole response object which is a circular object. You can store the data object key of the response. That should work just fine

mykoman
  • 1,715
  • 1
  • 19
  • 33
15

Today I had this problem and one way I managed to solve it was instead of return:

this.ssoContent = response;

I returned:

this.ssoContent = response.data;
Diana
  • 151
  • 1
  • 3
11

This also happens when you forget to put the keyword await in your async function.

Abdul Majeed
  • 111
  • 1
  • 2
5

'This also happens when you forget to put the keyword await in your async function.'

solved for me.

how silly I feel....

  • 2
    This is really just a "Thanks" for [another answer](https://stackoverflow.com/a/69603485/10871073) and should be deleted. – Adrian Mole Aug 23 '22 at 11:55
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Aug 23 '22 at 14:37
2

#2023

short answer:

const response = await axios(url, body, options );
return response.data;    

Long answer:

Do you remember the http request object ? when you make axios call , store the response and return the same. you basically return the whole http object which causes circular dependency. hence you extract only data object from it and return.

1

I have that's problem when my app(nest.js app) try to send request to another apps(Nest.js apps). The problem is response of server. I can not resolve it, instead use superagent library. https://www.npmjs.com/package/superagent It is resolved easily.

milad
  • 11
  • 1
1

I am using TypeORM with NestJS and got several times the following error:

TypeError: Converting circular structure to JSON
--> starting at object with constructor 'EntityMetadata'
|     property 'ownColumns' -> object with constructor 'Array'
|     index 0 -> object with constructor 'ColumnMetadata'
--- property 'entityMetadata' closes the circle

It was because I forgot the getOne() or getMany() at the end of my query builder.

0

You can use a 3rd-party helper for this: circular json. ref:https://www.npmjs.com/package/circular-json

Install it with: npm i circular-json OR npm i circular-json --force

code:

const CircularJSON = require('circular-json');
const obj=CircularJSON.stringify(object)

here object can be circular or normal json object.

Kalnode
  • 9,386
  • 3
  • 34
  • 62
aakash4dev
  • 774
  • 4
  • 13
0

It is not related to this issue, but if by any chance you came to this tread with this issue happened in React, it might also be because of using ? on an unknown type:

type Test = unknown
const test:Test
{test ? <div>test</div> : null}

This will throw this error, you can change it to:

{Boolean(test) ? <div>test</div> : null}
Naeem Baghi
  • 811
  • 2
  • 14
  • 29