【发布时间】:2017-07-14 15:27:20
【问题描述】:
我正在从服务器端向客户端发送一个对象,而客户端获取的对象与我发送的对象完全不同。这就是我的意思:
代码
服务器端代码:
//Basic setup for the example
var res={};
res.models=[];
res.models[0]={};
//The OLD (wrong) value
res.models[0]['id']="b4fd12f1-61ca-4445-b916-62617f1c0a78";
//The NEW (correct) value
res.models[0]['id']="fb8f83e2-e157-4e1e-8315-8e5f03b44691";
//Output what the id is, this is always the correct id!
console.log("res.models[0]['id']: ",res.models[0]['id']);
socket.emit("updateRealSeatSelect", res);
客户端代码:
socket.on("updateRealSeatSelect", function(data){
//Output the id when we get the object. This is always wrong!
console.log("res.models[0]['id']: "+data.models[0]['id']);
});
输出就是问题所在。这是我得到的:
输出
服务器端输出:(正确)
res.models[0]['id']: fb8f83e2-e157-4e1e-8315-8e5f03b44691
客户端输出:(错误!为什么不一样??)
res.models[0]['id']: b4fd12f1-61ca-4445-b916-62617f1c0a78
我有双重三重四重检查服务器正在发送正确的对象与正确的ID。 客户端拿到对象时,对象不一样,id错了!怎么会这样?
杂项
尝试:
-
我尝试将
res复制到一个新对象中,然后发送它,但这也没有用。像这样:var newres = res; socket.emit("updateRealSeatSelect", newres); -
我也尝试在发送对象时使用
JSON.parse和JSON.stringify,但这也无济于事。像这样:socket.emit("updateRealSeatSelect", JSON.stringify(res));
版本:
- Express 版本:3.5.2
- 节点版本:v6.5.0
- Socket.IO:v1.3.6
【问题讨论】:
-
如果没有分配错误的值会怎样?
-
@PM77-1 首先设置错误的值是为了表明socket io正在发送旧对象。在我的实际代码中,id 设置在其他地方,然后我替换该 id 并发送消息。所以我不能跳过那一步:(但是当我在服务器端输出对象时,它是正确的。我不知道为什么它在服务器端是正确的,而在客户端是错误的。
-
我没有提出任何建议。我只是想知道没有事先分配会发生什么。你能查一下吗?
-
我不能跳过这一步。跳过初始生成步骤会导致应用程序跳过所有步骤。
-
原始代码中的 id 是否设置为异步?
标签: javascript node.js sockets express socket.io