Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Send Map in express res.send

I’m working on a game with a friend and we need to send a Map with some stuff in it, but express only sends the user {} instead of the actual Map. The problem is at sending it and not the code itself, console.log‘ging it does return the Map.
Code:

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Generally, you can only send serializable values over the network. Maps aren’t serializable:

const map = new Map();
map.set('key', 'value');
console.log(JSON.stringify(map));

Either send an array of arrays that can be converted into a Map on the client side, or use another data structure, like a plain object. For example:

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 });
    }
});

Then on the client-side:

fetch(..)
    .then(res => res.json())
    .then((result) => {
        if ('error' in result) {
            // do something with result.error and return
        }
        const userDataMap = new Map(result);
        // ...

Or something along those lines.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading