Transmit the map via res.send in Express

My friend and I are collaborating on a game project, but we're encountering an issue when trying to send a Map with some data in it. Instead of receiving the actual Map, Express is sending the user {}. Strangely enough, when I use console.log to check the Map, it does display correctly. Here's the code snippet:

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

https://i.sstatic.net/7v4Fe.png https://i.sstatic.net/UmVLl.png

Answer №1

Typically, when sending data over the network, it is important to note that only serializable values can be transmitted. This means that maps are not serializable:

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

To work around this limitation, you could consider sending an array of arrays that can later be converted into a Map on the client side. Alternatively, using a different data structure like a plain object may also be a viable solution. Here's an 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);
        // ...

Consider implementing a similar approach for handling non-serializable data.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

attempting to shift course, but finding no success

I'm attempting to include dir=rtl or direction: rtl in the CSS, but it doesn't seem to have any effect on the browser and the content still displays left to right. What steps can I take to fix this? This template is pre-made from Colorlib. It&ap ...

What is the best way to create a cube in Three.js with the 4 corner points of the base and a specified height?

Given a JSON with base coordinates, I am looking to generate a cube in Three.js. The height of the cube will be a constant value, such as 1. { "points": [ { "x": 0, ...

Looking for a way to update a world map image by selecting multiple checkboxes to apply a flood fill color to different countries using Mogrify

Exploring different methods to achieve my goal, I am wondering if creating a web service where users can track visited countries on a world map can be done in a simpler way than using Javascript or Ajax. The idea is for users to mark the countries they hav ...

Using node.js with express to send data stored in a variable to the browser instead of displaying it in the

I'm currently getting the hang of node.js. It's pretty straightforward to use res.send and output some basic "hello world" text, but how can I pass variables to the browser instead of just to the console? Here is a snippet of code: var Tester = ...

Utilizing an external API in Javascript for fetching data

Is it permissible for me to directly initiate an API request from JavaScript to an external API (in this scenario at ) using the XMLHttpRequest object? If not, what steps should I take to retrieve data from this source? Do I need to incorporate a PHP bac ...

Update the value of a td element when a select option is changed in another td element within the same table row

I have a table set up as follows: Header1 | Header2 | Header3 | Header 4 | Header 5 Row 1 |<span>Some Text</span> | <select></select> Row 2 Row 3 . . . . Rows generated dynamically. My objecti ...

Initializing the $(this) variable prior to the function declaration

I am faced with the task of performing multiple checks based on the IDs of certain elements, all of which vary slightly. So, I created several functions to handle this, and rather than repeatedly using $(this).children ..., I wanted to create a short vari ...

"Upon clicking the login button, I encountered an issue with redirecting to the destination

I've been working on developing a login page using Angular framework. However, I'm facing an issue where I am unable to access the destination page after entering the login credentials. Below, you can find a snippet of the code from the login.com ...

Issue with remounting in Nextjs 13

import { useRouter, useSearchParams, usePathname } from 'next/navigation'; export function useQueryParams() { const pathname = usePathname(); const router = useRouter(); const searchParams = useSearchParams()!; const updateQu ...

Creating an array object in JavaScript using an integer variable involves utilizing the integer as the

I am trying to populate an array object with integer variables using the following code: for(i=1; i<=2; i++) arr[i].push({i:(100 * i)}) The expected result should be: arr = [{ 1:100,2:200},{1:100,2:200}] However, the issue is that the array is bein ...

Don't run a specific test in a Jest test file

Currently working with the Jest framework and managing a test suite. I'm in need of guidance on how to disable or skip a particular test. Despite searching through documentation online, I haven't been able to find a solution. If you have any in ...

Which is better for toggling between images/icons: a switch statement or a ternary operator?

I have a unique challenge where I am dealing with a dynamic list of thumbnails. Some of the items in this list are images, while others need to be represented by icons. My goal is to display either an image or an icon based on the contentType of each item. ...

After installing the latest version of [email protected], I encountered an error stating "Module 'webpack/lib/node/NodeTemplatePlugin' cannot be found."

Upon updating to nextjs version 10.1.3, I encountered an error when running yarn dev. Error - ./public/static/style.scss Error: Cannot find module 'webpack/lib/node/NodeTemplatePlugin' Require stack: - /path_to/node_modules/mini-css-extract-plugi ...

Ways to remove an item from firebase database

Currently, I am exploring ways to delete data stored in the Firebase database specifically under the requests category. Check out this example Below are the functions I have implemented to fetch and manipulate the data: export default { async contactArtis ...

Issues with Angular functionality

I'm a newcomer to Angular and I am trying to recreate this example from jsfiddle in order to experiment with nodes. However, I am encountering issues with the Angular setup. Firstly, the jsfiddle is causing confusion because the application names do n ...

Retaining the value of a textbox while moving to another page

On a specific page (let's call it the sample page), there are four text boxes with pre-filled values. There is a button on this page for navigating to the next page, which also has a back button that takes you back to the sample page. However, when re ...

How can I remove all "node_modules" except for the "mocha" package?

After deploying my app on Heroku, I need to remove the 'node_modules' folder while ensuring that my unit tests still function properly. I attempted to delete the 'node_modules' folder within the 'heroku-postbuild' script in t ...

When I run 'npm start', all I see is a blank screen. My app is not

I'm experiencing a blank page on the home screen. How do I fix this issue? I want to display my frontend and see my website, but instead I'm getting a "Cannot get/" error message. My frontend is built in React.js - how can I connect it with node. ...

Using JQuery live in combination with Disqus and Google Analytics is a powerful way to

I have implemented a function to overload my website url links with Ajax. Here is the code snippet: $(document).ready(function() { $('.insite').live("click", function(ev) { if ( history.pushState ) history.pushState( {}, document.tit ...

What is the process for obtaining a fresh token from Cognito using the frontend?

Currently, I am working with a react app that utilizes Cognito for user authentication. My main query revolves around making a call to Cognito using the refresh token in order to receive a new token. Despite researching various examples provided by Cognit ...