I have a Node.js project that uses s开发者_StackOverflow中文版ocket.io. In it, I try sending an object from the client to the server like this:
socket.send(JSON.stringify({'type':'msg','message':'test'}));
When it arrives on the server, I call JSON.parse
on it, and check if object.type == 'msg'
. When I run the code and call console.log(object.type)
it returns "msg"
, but object.type == 'msg'
returns false. What's going on here?
EDIT:
The relevant part of the code that is failing is:
client.on('message', function(message, client){
var envelope = JSON.parse(message);
console.log(envelope.type);
if(envelope.type == "msg") { console.log("yay!"); }
}
Whenever a message comes in, msg
is printed, but not yay!
.
Did you already try using non-literals as keys in your JSON message? I'm building a small chat server to explore socket.io, using JSON messages. Here's my relevant code:
Client-side:
var jsonMsg = {
action: 'SEND',
body: msg,
name: name.val()
};
socket.send(JSON.stringify(jsonMsg));
Please note that both msg and name.val() are string values, grabbed from the corresponding input fields.
Server-side:
client.on('message', function(m, c) {
// parse message
var msg = json.parse(m);
switch (msg.action) {
case 'SEND':
// send message to channel
var broadCast = {
posted: date.toReadableDate(new Date(), 'timestamp'),
message: msg.body,
name: msg.name
};
socket.broadcast(json.stringify(broadCast));
break;
}
});
Note: toReadableDate
is a custom prototype method.
The message is recieved correctly on the server- and on the client-side as broadcast.
Maybe it's a node bug? I've just tried it in 0.5.0-pre and it works fine in the limited context.
> message = JSON.stringify({'type':'msg','message':'test'})
'{"type":"msg","message":"test"}'
> var envelope = JSON.parse(message);
> console.log(envelope.type);
msg
> if(envelope.type == "msg") { console.log("yay!"); }
yay!
Other options might be an encoding issue (looks like "msg" on the terminal but isn't strictly those characters in the string?)
Your message must be in the format '{"type":"msg"}'.
精彩评论