Home > Blockchain >  TypeError: Converting circular structure to JSON when axios response is forwarded
TypeError: Converting circular structure to JSON when axios response is forwarded

Time:10-10

I have an API where I need to call another API inside the controller function. Which I do using Axios, but when I try to attach Axios's response on my original API's response, it throws this error: TypeError: Converting circular structure to JSON.

Here's a sample code snippet

const userController = async (req,res)=>{

const ax = await axios.put(someURL, reqBody)

res.status(200).json(ax)

}

I know it's nonsensical to do something like this and I know why this error is caused but could somebody explain to me How it's happening in this case?

CodePudding user response:

TypeError: Converting circular structure to JSON is when some property in the object is repeated in another inner object.

Axios response has these properties:

// `data` is the response that was provided by the server
data: {..your real json response..},
// `status` is the HTTP status code from the server response
status: 200,
// `statusText` is the HTTP status message from the server response
statusText: 'OK',
// `headers` the HTTP headers that the server responded with
headers: {},
// `config` is the config that was provided to `axios` for the request
config: {},
// `request` is the request that generated this response
request: {}

If you send the entire axios response object to be converted to json, some property in your real json response could repeat the name of private axios properties like: status, data config, etc

Fix

Try with ax.data instead use the entire axios response ax

  • Related