节点js和Redis未定义的JSON属性

当我尝试从redis函数获取JSON属性时,我得到了undefined。

当我使用这个控制台输出什么是假设:

redisClient.on("message", function(channel, data) { console.log("new message add in queue "+ data + " channel"); socket.emit(channel, data); }); 

安慰:

新消息添加队列{“消息”:“一个新的消息!”,“用户”:“John Doe”}频道

当我尝试从数据中获取属性时,我得到了undefined:

 redisClient.on("message", function(channel, data) { console.log("new message add in queue "+ data['message'] + " channel"); socket.emit(channel, data); }); 

新消息添加到队列中的未定义通道

我也试图得到这样的数据属性没有运气

 data.message 

这很奇怪,因为在我的客户端脚本中,我可以使用data.message,它工作得很好。

你得到的数据对象是一个string,而不是一个对象。 要得到消息,你应该做JSON.parse(data).message

通过查看redisClient的源代码,您可以注意到publish方法和on('message')事件正在使用string参数。 当使用JSON.parse ,build议将其封装在try/catch块中。 该string可能无效,并将引发错误。

 redisClient.on("message", function(channel, data) { try{ data=JSON.parse(data) } catch(e){ return console.log('data is not an JSON string',data) } console.log("new message add in queue "+ data['message'] + " channel"); socket.emit(channel, data); }) 

更多信息