繁体   English   中英

发送非圆形 JSON 时的 Express 中间件“TypeError: Converting circular structure to JSON”

[英]Express middleware "TypeError: Converting circular structure to JSON" when sending a non-circular JSON

I am using the following function as middleware and want to send the length of the array (req.session.songArray.length) as a JSON however any JSON I attempt to send through res gives the error below. 我知道圆形对象不能被 JSON 字符串化,但只是尝试使用 { num: 20 } 会出现此错误,我不知道为什么。 当我删除 res.status.json 行时,代码运行没有错误。 我正在使用 npm 包天才歌词和快速会话来获得洞察力。

async function initSongArray(req, res, next){
    const searches = await Client.songs.search(req.params.artist);
    let songNum = 0
    while((searches[songNum].artist.name.includes('&')) && req.params.and === 0){
        console.log("& detected")
        songNum++;
    }
    req.session.artist = searches[songNum].artist;
    req.session.songArray = await req.session.artist.songs({sort: 'popularity', perPage: 20, page: 1});
    req.session.currPage = 2
    console.log(req.session.songArray.length)
    res.status(200).json( { num: 20 } )
}

app.get('/artist/:artist/:and', initSongArray)

C:\Users\bgrie\Desktop\a\compsci.websites\typesiteNode\node_modules\express-session\index.js:598 var str = JSON.stringify(sess, function (key, val) { ^

TypeError:将循环结构转换为 JSON --> 从 object 开始,使用构造函数“客户端”| property 'songs' -> object with constructor 'SongsClient' --- property 'client' closes the circle at JSON.stringify () at hash (C:\Users\bgrie\Desktop\a\compsci.websites\typesiteNode\node_modules\ express-session\index.js:598:18) 在 isModified (C:\Users\bgrie\Desktop\a\compsci.websites\typesiteNode\node_modules\express-session\index.js:426:57) 在 shouldSave (C :\Users\bgrie\Desktop\a\compsci.websites\typesiteNode\node_modules\express-session\index.js:448:11) 在 ServerResponse.end (C:\Users\bgrie\Desktop\a\compsci.websites\ typesiteNode\node_modules\express-session\index.js:334:11) 在 ServerResponse.send (C:\Users\bgrie\Desktop\a\compsci.websites\typesiteNode\node_modules\express\lib\response.js:232: 10) 在 ServerResponse.json (C:\Users\bgrie\Desktop\a\compsci.websites\typesiteNode\node_modules\express\lib\response.js:278:15) 在 initSongArray (C:\Users\bgrie\Desktop\一个\compsc i.websites\typesiteNode\index.js:70:21) 在 processTicksAndRejections (node:internal/process/task_queues:96:5)

session 正在尝试将其数据序列化到 JSON 以便将其保存到 session 存储。 所以,你试图在 session 中放入一些东西,其中有一个循环引用,因此不能以这种方式序列化。 所以,显然, searches[songNum].artist不仅仅是一个简单的 object。 它必须具有对其他对象的引用,然后创建循环引用。

我建议您创建一个新的 object 并从searches[songNum].artist中分配一些您在 session 中实际需要的简单属性。

可能searches[songNum].artist中有一些数据库内容。 如果您的数据库具有.toObject()方法或类似的方法,则将其转换为普通的 object 可能会很有用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM