将循环结构转换为 JSON 时出错,同时将 json 从 Flask 发送到 Node.js

Error Converting circular structure to JSON, while sending json from Flask to Node.js

我正在尝试将 json 文件从我的 Flask 服务器发送到我的 Node.js 服务器。不幸的是,在 node.js 方面我收到错误:

TypeError: Converting circular structure to JSON
    --> starting at object with constructor 'ClientRequest'
    |     property 'socket' -> object with constructor 'Socket'
    --- property '_httpMessage' closes the circle
    at JSON.stringify (<anonymous>)

在阅读了 SOF 中的其他问题后,我不确定为什么在我的特定情况下会出现此错误。

我的代码在 Flask 中看起来像这样

receipt.py

receiptDict = [
    {
        "date" :"some date",
        "receipt_id": "4456gdffd", 
        "store": "some store", 
        "items" : [{"name":"can of paint", "amount":1, "price":10}, 
        {"name":"bags of sand", "amount":2, "price":5} ],
        "total" : 15
    },
    
    { 
        "date" :"some date",
        "receipt_id": "44575fh",
        "store": "some store",
        "items" : [{"name":"screws", "amount":100, "price":100} ],
        "total" : 15
    }
        ]
main.py

from receipt import receiptDict
from flask import Flask
import json
app = Flask(__name__)


@app.route('/')
def index():
    #convert_json = json.dumps(receiptDict)
    #return convert_json 
    ·return 'hello flask' I get the same error with both returns

if  __name__ == '__main__':
    app.run(debug=True)

这是我在 node.js

中的控制器
dashboard.js

getReceiptInfo : async(req, res) =>{
        const receipt = await axios.get('http://127.0.0.1:5000')
        return res.send(receipt)

    }

使用jsonify,它会将数据序列化为JSON。

from receipt import receiptDict
from flask import Flask, jsonify # <--- import this jsonify here
import json
app = Flask(__name__)


@app.route('/')
def index():
    return jsonify(receiptDict)

if  __name__ == '__main__':
    app.run(debug=True)

有关 jsonify

的更多信息

也在你的控制器上做

 return res.send(receipt.data)

axios 默认将响应转换为 JSON,使用 <response>.data 而不是 <response>