代码之家  ›  专栏  ›  技术社区  ›  DNAScanner

在express res中发送地图。发送

  •  0
  • DNAScanner  · 技术社区  · 2 年前

    我正在和一个朋友制作一个游戏,我们需要发送一张包含一些内容的地图,但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");
        }
    });
    

    Console output Express respond (client used doesn't change anything)

    1 回复  |  直到 2 年前
        1
  •  1
  •   CertainPerformance    2 年前

    通常,您只能通过网络发送可序列化的值。映射不可序列化:

    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);
            // ...
    

    或者类似的东西。