ChuChuwi
ChuChuwi

Reputation: 1060

TypeError: Converting circular structure to JSON --> starting at object with constructor 'ClientRequest'

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 :)

Upvotes: 84

Views: 203337

Answers (13)

Yurii Hierts
Yurii Hierts

Reputation: 1930

Wrong usage:

All this objects I'm try to return are complex objects with a circular stuff.

@Post()
async someRequestName() {
  return this.httpService.post( // this is Observable<AxiosResponse>
    'http://localhost:3001/api/some-endpoint',
  );
}
@Post()
async someRequestName() {
  return firstValueFrom( // this is Promise<Observable<AxiosResponse>>
    this.httpService.post(
      'http://localhost:3001/api/some-endpoint',
    ),
  );
}
@Post()
async someRequestName() {
  const data = await firstValueFrom(
    this.httpService.post(
      'http://localhost:3001/api/some-endpoint',
    ),
  );
  return data; // this is as well Promise<Observable<AxiosResponse>>
}

Correct usage:

data.data includes only returned value from request. No circular stuff inside.

@Post()
async someRequestName() {
  const data = await firstValueFrom(
    this.httpService.post(
      'http://localhost:3001/api/some-endpoint',
    ),
  );
  return data.data; // this is JSON response
}

Summarize

Methods with decorators as @Post(), @Get() and etc, should return simple object (JSON), not complex object with methods and circular refs. You can't pass methods and circular refs over http protocol.

Upvotes: 3

Saoud Ahmed Khan
Saoud Ahmed Khan

Reputation: 11

I am facing this error just because I am wrapping object in to an object. bolded line cause error in my case

 for (const record of records) {
     const { createdAt } = record;
     const dateOnly = createdAt.toISOString().split('T')[0]
     if (!organizedData[`${dateOnly}`]) {
         organizedData[`${dateOnly}`] = [];
         }
     const joinedData = { ...record }; //<<< This is causing error for me>>>
     organizedData[`${dateOnly}`].push(joinedData);
}

Upvotes: 0

gourav espire
gourav espire

Reputation: 11

Today I had this problem and invest lots of time. It is working for me.

from this.ssoContent = response;

To this.ssoContent = response.data;

Upvotes: 1

M. Hamza Rajput
M. Hamza Rajput

Reputation: 10276

Fix for me is to not stringify axios response object.

wrong

const payload = { name: "M Hmzara Rajput" }
console.log("request:", JSON.stringify(payload));
const response = await axios.post(`http://server:port/endpoint`, payload);
// Don't JSON.stringify to an http object instead response.data
console.log("response:", JSON.stringify(response));

right

const payload = { name: "M Hmzara Rajput" }
console.log("request:", JSON.stringify(payload));
const response = await axios.post(`http://server:port/endpoint`, payload);
console.log("response:", JSON.stringify(response.data));

Upvotes: 1

Raviraj Gardi
Raviraj Gardi

Reputation: 298

#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.

Upvotes: 9

aakash4dev
aakash4dev

Reputation: 1176

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.

Upvotes: 0

Naeem Baghi
Naeem Baghi

Reputation: 831

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}

Upvotes: 0

Alexis TONNEAU
Alexis TONNEAU

Reputation: 61

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.

Upvotes: 3

Diana
Diana

Reputation: 441

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;

Upvotes: 34

milad
milad

Reputation: 11

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.

Upvotes: 1

Abdul Majeed
Abdul Majeed

Reputation: 119

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

Upvotes: 11

mykoman
mykoman

Reputation: 1905

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

Upvotes: 19

LuckyLuke
LuckyLuke

Reputation: 1054

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

Upvotes: 52

Related Questions