Mrugesh
Mrugesh

Reputation: 4517

axios gives me converting circular structure to json error while sending the data

My code is as shown below:

axios.post('https://api.sandbox.xyz.com/v1/order/new', JSON.stringify({
            "request": "/v1/order/new",
            "nonce": 123462,

            "client_order_id": "20150102-4738721",
            "symbol": "btcusd",
            "amount": "1.01",
            "price": "11.13",
            "side": "buy",
            "type": "exchange limit"
        }), config)
        .then(function(response) {
            console.log(response);
            res.json({
                data: JSON.stringify(response)
            })
        })
        .catch(function(error) {
            console.log(error);
            res.send({
                status: '500',
                message: error
            })
        });

Now it is saying that Unhandled promise rejection (rejection id: 2): TypeError: Converting circular structure to JSON for the code res.json({data:JSON.stringify(response)})

So, is there anything missing in this code ?

Upvotes: 45

Views: 64234

Answers (7)

OSA413
OSA413

Reputation: 486

In case if you are using Axios for e2e test in your Jest/Vitest tests, you can use the following interceptor to minimize the noise that Axios produces and/or make your rejected promises more readable.

const SimplifyAxiosError = (err: AxiosError) => {
    let result: Error = err;
    if (err.response) {
        result = new Error((err.response.data as any).statusCode
            ?? (err.response.data ? JSON.stringify(err.response.data) : null)
            ?? String(err.response.status))
        // This makes it that the stack trace shows the request that caused the error
        result.stack = err.stack;
    }
    throw result;
}

const ax = axios.create(/* config here */)
ax.interceptors.response.use(x => x, SimplifyAxiosError);

Upvotes: 0

Surya
Surya

Reputation: 662

This happens many a time with axios because sometimes we directly return the response from the endpoint. For example, this error will occur if we pass the response directly, rather than passing the response.data.

response = await axios.get("https://jsonplaceholder.typicode.com/users");
res.send(response); // error
res.send(response.data); // works perfectly

Upvotes: 23

Ken Mbogo
Ken Mbogo

Reputation: 191

This worked for me.

res.status(200).json({
   data: JSON.parse(JSON.stringify(response.data)
}));

Upvotes: 9

Satya
Satya

Reputation: 1779

The problem might be because of the response you are sending out to the client is not a JSON object. In my case, I solved the error by simply sending the JSON part of the response object.

res.status(200).json({
  success:true,
  result:result.data
})

Upvotes: 12

Minh Nguyen
Minh Nguyen

Reputation: 2039

Try to add error handler interceptor:

const handle_axios_error = function(err) {

    if (err.response) {
        const custom_error = new Error(err.response.statusText || 'Internal server error');
        custom_error.status = err.response.status || 500;
        custom_error.description = err.response.data ? err.response.data.message : null;
        throw custom_error;
    }
    throw new Error(err);

}

axios.interceptors.response.use(r => r, handle_axios_error);
axios.post(....)

Thanks Sepehr Vakili for his post https://github.com/axios/axios/issues/836#issuecomment-390342342

Upvotes: 5

Shadab
Shadab

Reputation: 403

res.json({ data: JSON.stringify(response.data) });

This worked for me.

Upvotes: 6

thomasmeadows
thomasmeadows

Reputation: 1881

axios.post('https://api.sandbox.xyz.com/v1/order/new', JSON.stringify({
            "request": "/v1/order/new",
            "nonce": 123462,
            "client_order_id": "20150102-4738721",
            "symbol": "btcusd",
            "amount": "1.01",
            "price": "11.13",
            "side": "buy",
            "type": "exchange limit"
        }), config)
        .then(function(response) {
            res.send(response.data)
        })
        .catch(function(error) {
            res.send({
                status: '500',
                message: error
            })
        });

Upvotes: 37

Related Questions