【问题标题】:How to solve: TypeError: Converting circular structure to JSON. Using Node and express如何解决:TypeError:将循环结构转换为 JSON。使用 Node 和 express
【发布时间】:2021-05-11 13:11:02
【问题描述】:

我正在尝试通过其 ID 从 CosmosDB 获取单个项目。我正在使用res.send(docResponse) 将响应发送给邮递员,但这给了我一个错误,我正在使用邮递员来测试 Api。

app.get('/:id', async (req, res) => {

    try {
        var id = req.params.id;

        const dbResponse = await cosmosClient.databases.createIfNotExists({
            id: databaseId
        });
        let database = dbResponse.database;
            
        const { container } = await database.containers.createIfNotExists({id: containerId});

        const docResponse = await container.item(id, 1).read();

        // res.send(docResponse)
        res.json(docResponse);

        
    } catch (error) {
        
        console.log(error);
        res.status(500).send("Error with database query: " + error.body);
        
    }

})

我也用过res.json(docResponse),但错误是一样的。

我认为这是一个错误

TypeError: Converting circular structure to JSON
    --> starting at object with constructor 'CosmosClient'
    |     property 'databases' -> object with constructor 'Databases'
    --- property 'client' closes the circle
    at JSON.stringify (<anonymous>)
    at stringify (C:\Users\abbas.haider\Desktop\node azure\node_modules\express\lib\response.js:1123:12)
    at ServerResponse.json (C:\Users\abbas.haider\Desktop\node azure\node_modules\express\lib\response.js:260:14)
    at C:\Users\abbas.haider\Desktop\node azure\app.js:92:13

【问题讨论】:

  • quite a number of questions about that error on Stack Overflow 或许你可以看一下,看看有没有回答你的问题?
  • console.log(docResponse) 给你什么?
  • 尝试 res.resource;
  • @SomeoneSpecial console.log(docResponse) 给出正确的输出。只有当我尝试重新发送时才会出错。
  • 您可以尝试在响应中发送 docResponse.item 吗?根据文档,read 返回一个对 ItemResponse 的承诺。 read(options?: RequestOptions): Promise>.. 这里的 itemresponse 对象有一个属性“item”。

标签: javascript node.js express azure-cosmosdb


【解决方案1】:

改用res.send(docResponse.resource);?这是我的测试结果。

这里有一个vivid explanation关于这个错误,根据错误信息,很明显docResponse不是一个合适的响应对象,你需要手动提取响应对象。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-02-03
    • 2021-10-21
    • 2014-01-21
    • 1970-01-01
    • 2019-06-11
    • 2022-01-11
    • 2019-08-25
    相关资源
    最近更新 更多