我有一个在 node.js 中创建的 set
,我尝试使用 res.send
或 res.json
通过 Express.js
将其发送到客户端,但该集合在客户端始终显示为空。这是我的代码:
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 ({})
});
为什么会发生这种情况?这是 Express.js 的问题吗?
最佳答案
Express response.json
函数使用 JSON.stringify
发送数据。并且因为 JSON.stringify
忽略除函数之外的所有符号键控属性。这就是为什么您在客户端上收到一个空对象。
查看JSON.stringify的更多信息
console.log(JSON.stringify({ prop: 5, foo() {}, [Symbol('s')]: 'symbol' }));
// -> "{"prop":5}"
console.log(JSON.stringify(new Set([1, 'two', null])));
// -> "{}"
关于javascript - Express.js不是 `res.send`集吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48995280/