通常,您只能通过网络发送可序列化的值。映射不可序列化:
const map = new Map();
map.set('key', 'value');
console.log(JSON.stringify(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);
// ...
或者类似的东西。