发送数据时,axios使我将圆形结构转换为json错误

Mru*_*ker 5 node.js axios

我的代码如下所示:

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
            })
        });
Run Code Online (Sandbox Code Playgroud)

现在说Unhandled promise rejection (rejection id: 2): TypeError: Converting circular structure to JSON 的是代码res.json({data:JSON.stringify(response)})

那么,此代码中是否缺少任何内容?

Sur*_*rya 21

这种情况经常发生,axios因为有时我们直接从端点返回响应。例如,如果我们直接传递响应而不是传递response.data.

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

  • 你是对的,这对我来说效果很好! (2认同)

tho*_*ows 6

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
            })
        });
Run Code Online (Sandbox Code Playgroud)

  • 非常感谢。在问题上花了几个小时,我需要更改的只是我对response.data的响应。 (4认同)
  • 这实际上是一个伟大而简单的答案!荣誉! (2认同)

小智 6

问题可能是因为您发送给客户端的响应不是 JSON 对象。就我而言,我通过简单地发送响应对象的 JSON 部分解决了错误。

res.status(200).json({
  success:true,
  result:result.data
})
Run Code Online (Sandbox Code Playgroud)


小智 5

res.json({ data: JSON.stringify(response.data) });
Run Code Online (Sandbox Code Playgroud)

这对我有用。


Ken*_*ogo 5

这对我有用。

res.status(200).json({
   data: JSON.parse(JSON.stringify(response.data)
}));
Run Code Online (Sandbox Code Playgroud)