简体   繁体   English

如何使用 socket.io 向客户端发出未定义/空值?

[英]How to emit undefined/null value to client with socket.io?

I recently discovered that the socket.io parser seems to strip keys with undefined/null values from emitted data objects.我最近发现socket.io解析器似乎从发出的数据对象中删除了带有未定义/空值的键。 This is undesirable as i'm trying to use these values to clear information from my views.这是不可取的,因为我试图使用这些值来清除我观点中的信息。

Does anyone know a work around for this?有没有人知道解决这个问题? The API allows you to provide your own parser but i'd prefer not to go down that route or alter the defualt parser ( socket.io-parser ). API 允许您提供自己的解析器,但我不想走这条路或更改默认解析器( socket.io-parser )。

I haven't seen this specific behavior.我还没有看到这种特定的行为。 A quick workaround could be to always send a boolean parameter isUndefined or isNull and check it at the other end.一个快速的解决方法可能是始终发送一个布尔参数isUndefinedisNull并在另一端检查它。

Same behaviour is observed on JSON.stringify() (which I suspect socket.io is using) and also undefined is not a valid JSON token.JSON.stringify() (我怀疑 socket.io 正在使用)上观察到相同的行为,并且undefined也不是有效的 JSON 令牌。

You could replace undefined with whatever you want before sending.在发送之前,您可以将 undefined 替换为您想要的任何内容。 Either as null or as some custom string and do the necessary checks on the other end作为空值或一些自定义字符串,并在另一端进行必要的检查

const dataToEmit = { something: undefined };

const replaceWith = null;
const s = JSON.stringify(dataToEmit, (k, v) => v === undefined? replaceWith : v );
const dataParsed = JSON.parse(s)

socket.emit("channel_name", dataParsed);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM