'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 ?
Solution 1:[1]
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
})
});
Solution 2:[2]
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
})
Solution 3:[3]
This worked for me.
res.status(200).json({
data: JSON.parse(JSON.stringify(response.data)
}));
Solution 4:[4]
res.json({ data: JSON.stringify(response.data) });
This worked for me.
Solution 5:[5]
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
Solution 6:[6]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | thomasmeadows |
| Solution 2 | glinda93 |
| Solution 3 | Romanas |
| Solution 4 | Shadab |
| Solution 5 | Minh Nguyen |
| Solution 6 | Surya |
