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

Viewed 35075

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 ?

6 Answers

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

This worked for me.

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

This worked for me.

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(reponse.data) // works perfectly

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

Related