发送非循环 JSON 时快速"TypeError: Converting circular structure to JSON"中间件



我使用以下函数作为中间件,并希望将数组的长度(req.session.songArray.length(作为JSON发送,但我试图通过res发送的任何JSON都会出现以下错误。我知道循环对象不能被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:598var str=JSON.stringfy(sess,function(key,val({^

TypeError:将循环结构转换为JSON-->在具有构造函数"Client"的对象处启动|属性"songs"->具有构造函数"SongsClient"的对象---属性"client"关闭圆圈位于JSON.stringify((at hash(C:\Users\bgrie \Desktop\a\compasci.websites\typesiteNode\node_modules\express session\index.js:598:18(at isModified(C:\Users\bgrie \Desktop\a\compasci.websites\typesiteNode\node_modules\express session\index.js:442:57(at shouldSave(C:\Users\bgrie \Desktop\a\compasci.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\compasci.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\a\compsci.websites\typesiteNode\index.js:70:21(在processTicksAndRejections(节点:internal/process/task_queues:96:5(

会话正试图将其数据序列化为JSON,以便将其保存到会话存储中。因此,您试图在会话中放入具有循环引用的内容,因此无法以这种方式序列化。因此,显然,searches[songNum].artist不仅仅是一个简单的对象。它必须具有对其他对象的引用,然后创建循环引用。

我建议您创建一个新对象,并从searches[songNum].artist中分配一些会话中实际需要的简单属性。

searches[songNum].artist可能有一些数据库的东西。如果你的数据库有.toObject()方法或类似的东西,把它变成一个普通对象可能会很有用。

最新更新