Issue: JSON conversion error caused by a circular structure originating from an object created with constructor 'ClientRequest'

As a beginner in nest.js, I am attempting to incorporate Axios into my code. However, I have encountered an error that I would like assistance in resolving.

    --> 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 the content of my app.service.ts file:

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;

    }

Additionally, here is the code from my app.controller.ts file:

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

Your help in resolving this issue would be greatly appreciated. Thank you :)

Answer №1

One great feature of nest.js is the HttpService, which comes built-in and can be easily injected using Dependency Injection: https://docs.nestjs.com/techniques/http-module

Another important point to consider is that trying to store the entire response object can lead to issues due to its complex data structure and potential circular dependencies, resulting in errors like (TypeError: Converting circular structure to JSON)

Instead of storing the whole object, it's recommended to map only the necessary data,

Alternatively, you could explore libraries that handle circular JSON parsing effectively: https://www.npmjs.com/package/flatted

Answer №2

Recently, I encountered an issue and found a solution by making a small change in my code. Instead of simply assigning the response to a variable using this.ssoContent = response;, I opted to assign only the data within the response object like this:

this.ssoContent = response.data;

Answer №3

Instead of keeping the entire circular response object in storage, it's sufficient to store just the data object key from the response. This approach should function effectively.

Answer №4

Forgetting to include the keyword await in your async function can lead to this issue as well.

Answer №5

#2024

Summary:

const result = await fetch(url, options);
return result.json();    

Detailed explanation:

Have you ever worked with the fetch API in JavaScript? When you send a request using fetch, make sure to extract and return only the data object from the response to avoid circular dependency issues.

Answer №6

Encountered an issue while using TypeORM in conjunction with NestJS where I kept running into the same 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

I later realized that the reason for this error was due to missing getOne() or getMany() method calls at the end of my query builder.

Answer №7

The Issue of Incorrect Implementation:

All the objects I'm attempting to return are intricate with circular references.

@Post()
async someRequestName() {
  return this.httpService.post( // responseType is Observable<AxiosResponse>
    'http://localhost:3001/api/some-endpoint',
  );
}
@Post()
async someRequestName() {
  return firstValueFrom( // responseType becomes 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; // responseType still remains as Promise<Observable<AxiosResponse>>
}

Recommendation for Correct Usage:

data.data contains only the returned value from the request, without any circular references.

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

Key Takeaway:

It is crucial for methods using decorators like @Post(), @Get(), etc., to return simple JSON objects instead of complex ones with methods and circular references. Transmission of methods and circular references over HTTP protocol is not supported.

Answer №8

Encountered an issue when my Nest.js app attempted to send requests to other Nest.js apps. The problem stemmed from the server's response, which proved difficult to troubleshoot. Fortunately, I found a solution by utilizing the superagent library. https://www.npmjs.com/package/superagent Resolving the problem was a straightforward process.

Answer №9

To avoid issues, refrain from stringifying the axios response object.

incorrect

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

correct

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

Answer №10

Recently, I encountered a challenge that required significant time investment to resolve. Fortunately, my efforts paid off in the end.

Changing the line from "this.ssoContent = response;" to "this.ssoContent = response.data;" solved the issue for me.

Answer №11

Although it may not directly address the current issue at hand, if you happen to stumble upon this thread while encountering a similar problem in React, it could be due to using ? on an unknown type:

type Example = unknown
const example:Example
{example ? <div>example</div> : null}

This would result in an error being thrown, but you can resolve it by changing it to:

{Boolean(example) ? <div>example</div> : null}

Answer №12

If you encounter circular JSON in your code, consider using a third-party solution like circular-json. Check it out here: https://www.npmjs.com/package/circular-json

To add this tool to your project, run either of these commands: npm i circular-json OR npm i circular-json --force

Implementation example:

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

In this scenario, 'object' can be either a circular or normal JSON object.

Answer №13

My code is throwing an error because I made the mistake of wrapping an object inside another object. The bolded line is causing the issue in my scenario.

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

typescript import { node } from types

Exploring the possibilities with an electron application developed in typescript. The main focus is on finding the appropriate approach for importing an external module. Here is my typescript configuration: { "compilerOptions": { "target": "es6", ...

Typescript subtraction operation may result in Undefined

I am a beginner in the world of TypeScript and I'm currently struggling with running this code snippet: class TestClass { public t: number = 10; constructor() { this.t = this.t - 1; console.log(this.t); } } var obj = new TestClass(); ...

Issues with TypeScript arise when transferring arguments between functions

Encountering a TypeScript error due to this pattern: Error message: 'Argument of type '(string | number)[]' is not assignable to parameter of type 'string[] | number[]' function foo(value: string | number) { return bar([va ...

Issue: Unable to find suitable routes for navigation. URL Segment: 'profile' or Encounter: Server could not load resource as response status is 401 (Unauthorized)

Currently, I am working on the MEANAUTH application and encountering an issue with accessing user profiles using angular jwt. When attempting to log in and access user profiles at https://localhost:3000/profile, I receive the following error message: Faile ...

I am experiencing difficulties with my data not reaching the function in my component.ts file within Angular

My current project involves integrating Google Firebase to handle the login functionality. I encountered an issue where the data inputted from the HTML page to the component.ts file was not being processed or reaching Firebase. However, when I initialized ...

Securing React: Best Practices for State Management

Consider the following scenario: const UserProfile: React.FC<RouteComponentProps> = (props) => { const { isAdmin} = useContext(GlobalContext); if (isAdmin()) { return <CriticalFeature/>; } else { return <NonCritic ...

Injecting Variables Into User-Defined Button

Presenting a custom button with the following code snippet: export default function CustomButton(isValid: any, email: any) { return ( <Button type="submit" disabled={!isValid || !email} style={{ ...

Issues occur during installation of Angular on Mac Catalina, encountering errors while trying to run the installation command for Angular: `% sudo npm

My npm version is 6.14.6 and node version is v12.18.3. I have attempted the following: Added sudo in the beginning, but still not working. Tried to install har-validator using command: sudo npm install har-validator Attempted: npm install --force expo-cli ...

Pass an array of objects to an Angular 8 component for rendering

Recently, I started working with Angular 8 and faced an issue while trying to pass an array of objects to my component for displaying it in the UI. parent-component.ts import { Component, OnInit } from '@angular/core'; @Component({ selector: ...

Guide to implementing Telegram authorization in an Angular application

Having trouble integrating telegram authorization into my Angular project. I've set up a bot and added the correct host settings on Windows. Following this guide, I have implemented the code as suggested. However, I am encountering an error: Refused ...

What is the best way to send an enum from a parent component to a child component in

I'm trying to send an enum from a parent component to a child component. This is the enum in question: export enum Status { A = 'A', B = 'B', C = 'C' } Here's the child component code snippet: @Component({ ...

Iterating through all numbers to remove their colors in a React application

I have a function that successfully changes the color of all child buttons when clicked. Now, I need to create a "ClearGame" button that resets all button background colors back to their original state '#ADC0C4'. How can I achieve this using the ...

The type 'Text' does not have a property named 'then'

Transitioning from .js to typescript. When I changed the file extension from .js to .ts while keeping the same code, I encountered an error stating Property 'then' does not exist on type 'Text'.ts in the then((value) method. The return ...

Experiencing a CORS issue with React when an API that redirects to the same domain returns a

I am encountering an issue with my React web application (a.com) as it communicates with an API (b.api) using axios/XHR requests. Specifically, there is a request that the server responds to with a 302 redirect to another location within a.com. However, t ...

How can I inform Typescript that an interface will exclusively consist of defined members?

My interface looks like this interface Person { name?:string; age? :number; gender?:string } I need to reuse the same interface type, but with a modification indicating that all members will never be undefined. The updated version would look like this: ...

The inference of optional generic types is not occurring

I need help addressing a type error in my TypeScript wrapper for handling NextJS API requests. Specifically, I am facing an issue when trying to pass a single type for one of the generic types in the function. To illustrate this error, I have created a si ...

Adding 30 Days to a Date in Typescript

Discovering Typescript for the first time, I'm attempting to calculate a date that is (X) months or days from now and format it as newDate below... When trying to add one month: const dateObj = new Date(); const month = dateObj.getUTCMonth() + 2; con ...

There was a problem uploading the Feed document using amazon-sp-api: Invalid initialization vector encountered

I'm encountering an issue while attempting to upload a Feed document to Amazon using the createFeedDocument operation of the Selling Partner API. Following the API call, I received a response object that includes the feedDocumentId, url, and encryptio ...

Trying to create a function in TypeScript that works like lodash's "bindKey"?

I am looking to create a function that serves as a shortcut for obj.func.bind(obj). It should work like this: const bound = <...>(obj: ..., fnKey: ...) : ... => obj[fnKey].bind(obj); const obj = { a: "abc", b() { console.log(thi ...

Using Enum Constants for @switch in Angular 17

I am looking to utilize the new angular @switch statement to display different elements based on an Enum. enum State { Loading, Loaded, Error } @Component({ ... }) export class MyComponent { state: State = State.Loading; } @switch (state) { @c ...