我正在和一個朋友一起做一個游戲,我們需要發送一個包含一些東西的地圖,但是 express 只發送用戶{}而不是實際的地圖。問題在于發送它而不是代碼本身,console.log它確實回傳了地圖。代碼:
router.get("/list", async (req, res) => {
try {
const users = await userCollection.find();
accessedListEmbed(req);
let userData = new Map();
users.forEach((user) => userData.set(user.userName, user.status));
res.send(userData);
console.log(userData);
} catch (error) {
res.send("unknown");
}
});

uj5u.com熱心網友回復:
通常,您只能通過網路發送可序列化的值。地圖不可序列化:
const map = new Map();
map.set('key', 'value');
console.log(JSON.stringify(map));
要么發送一個可以在客戶端轉換為 Map 的陣列陣列,要么使用其他資料結構,如普通物件。例如:
router.get("/list", async (req, res) => {
try {
const users = await userCollection.find();
accessedListEmbed(req);
const userDataArr = [];
users.forEach((user) => {
userDataArr.push([user.userName, user.status]);
});
res.json(userDataArr); // make sure to use .json
} catch (error) {
// send JSON in the case of an error too so it can be predictably parsed
res.json({ error: error.message });
}
});
然后在客戶端:
fetch(..)
.then(res => res.json())
.then((result) => {
if ('error' in result) {
// do something with result.error and return
}
const userDataMap = new Map(result);
// ...
或類似的規定。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/489764.html
標籤:javascript 表示
上一篇:可選引數未定義
