我正在尝试使用socket.io-client
发送请求:
socket.emit('eventName', {
name: 'john doe',
phone: undefined,
})
问题是服务器端socket.io
收到了这个:
socket.on('eventName', obj => {
console.log(obj) // {name: 'john doe'}
})
所有等于undefined的属性都会被删除。
答案 0 :(得分:1)
socket.io的数据格式为JSON,JSON format specification不包含undefined
值。
JSON值可以是object
,array
,number
,string
,true
,false
或{{1} }。
因此,当socket.io在内部调用null
时,它会跳过任何没有这些有效值的属性。
这是MDN描述JSON.stringify()
的行为的方式:
如果未定义,在转换过程中遇到函数或符号,则省略(在对象中找到它)或删除为null(在数组中找到它时)。传入JSON.stringify(function(){})或JSON.stringify(undefined)等“纯”值时,JSON.stringify也可以返回undefined。
因此,您需要将要发送的任何属性的值设置为其中一个有效值。在这种特殊情况下,您可以将其设置为JSON.stringify()
或空字符串。
答案 1 :(得分:-1)
如果你想发送空数据不要使用undefined它意味着你擦除那些数据而不是使用它:
socket.emit('eventName', {
name: 'john doe',
phone: '',
})
那样电话仍然被声明但未定义并且空了