Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

236
Views
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)

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!