I have a set
that I create in node.js and I am trying to send it to the client with Express.js
using res.send
or res.json
but the set always appears empty on the client side. This is my code:
app.get('/test-endpoint', function(req, res) {
let set1 = new Set();
set1.add('SOME ITEM');
console.log('Set 1:', set1); // logs out set1 correctly in the terminal (Set 1 Set: { 'SOME ITEM' })
res.json(set1); // when this gets to the client side it is an empty set ({})
});
Why is this happening? Is it an Express.js issue?
Express response.json
function uses JSON.stringify
to send the data. And because JSON.stringify
ignore all Symbols-keyed properties in addition to functions . That's why you receive an empty object on the client.
Check more info of JSON.stringify
console.log(JSON.stringify({ prop: 5, foo() {}, [Symbol('s')]: 'symbol' })); // -> "{"prop":5}" console.log(JSON.stringify(new Set([1, 'two', null]))); // -> "{}"
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.