Axios POST请求报错:TypeError: Converting circular structure to JSON
问题:Axios POST请求返回循环引用JSON错误
我尝试用Axios向API发送POST请求,请求体包含Candidates和Items两个嵌套列表的对象,请求时出现了循环引用转JSON的错误,相关代码、请求体和错误信息如下:
请求代码
algoController.calculate = async (req, res) => { const config = { headers:{ "api-key": process.env.PERSONAL_API_KEY, 'Content-Type': 'application/json' } }; console.log(req.body.data); console.log(config); res.send( await axios.post(process.env.API_ADDRESS, req.body.data, config)).data };
请求体日志
{ Candidates: [ { Width: 5000, Length: 5000, Height: 5000, MaxWeight: 1000000 } ], Items: [ { Width: 20, Length: 16, Height: 10, Weight: 0, TagOrColor: '#00be00', Quantity: 10 } ] }
错误信息
C:\Users\tlege\OneDrive\Masaüstü\bindrake\node_modules\express\lib\response.js:1150 : JSON.stringify(value); ^ TypeError: Converting circular structure to JSON --> starting at object with constructor 'ClientRequest' | property 'socket' -> object with constructor 'TLSSocket' --- property '_httpMessage' closes the circle at JSON.stringify (<anonymous>) at stringify (C:\Users\tlege\OneDrive\Masaüstü\bindrake\node_modules\express\lib\response.js:1150:12) at ServerResponse.json (C:\Users\tlege\OneDrive\Masaüstü\bindrake\node_modules\express\lib\response.js:271:14) at ServerResponse.send (C:\Users\tlege\OneDrive\Masaüstü\bindrake\node_modules\express\lib\response.js:162:21) at algoController.calculate (C:\Users\tlege\OneDrive\Masaüstü\bindrake\controllers\algoController.js:14:7) at processTicksAndRejections (node:internal/process/task_queues:96:5)
解决方案
错误核心是括号位置错误:你把.data放在了res.send()的外面,导致res.send()接收的是整个Axios响应对象(包含socket等存在循环引用的属性),而非接口返回的纯数据。
修正后的代码(两种写法任选其一):
写法一:拆分步骤更清晰
algoController.calculate = async (req, res) => { const config = { headers:{ "api-key": process.env.PERSONAL_API_KEY, 'Content-Type': 'application/json' } }; console.log(req.body.data); console.log(config); // 先获取完整响应,再提取数据部分 const apiResponse = await axios.post(process.env.API_ADDRESS, req.body.data, config); res.send(apiResponse.data); };
写法二:简洁链式调用
algoController.calculate = async (req, res) => { const config = { headers:{ "api-key": process.env.PERSONAL_API_KEY, 'Content-Type': 'application/json' } }; console.log(req.body.data); console.log(config); // 将.data移到await的括号内,确保发送的是纯数据 res.send( (await axios.post(process.env.API_ADDRESS, req.body.data, config)).data ); };
调整后就能正确提取接口返回的纯数据,避免循环引用无法转JSON的问题。
内容的提问来源于stack exchange,提问作者Bot Ellis
相关产品推荐
相关产品推荐

