簡體   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