Socket.io return 作为数据为空,但服务器正在接收数据

Socket.io return null as data but server is receiving the data

我是节点、快递、mongodb 和 socket.io 的新手。到目前为止,一切都非常顺利。所以我正在构建这个小型测试应用程序,用户输入他的名字,然后 post 一个问题。

socket.io 接收数据(用户名和问题),但返回数据时显示为空。 (一开始它是有效的,但后来我开始安装猫鼬,从那时起就出了问题)。我使用 express 框架并安装了所有必要的模块。

在我的视图中这是连接到套接字和更新数据的代码:

<script>
    $(document).ready(function()
    {
        var socket = io();

        $("#btnAskQuestion").on("click", function(e)
        {
            //get the value of the inputfield and textarea
            var username = $('#inputQuestion').val();
            var question = $('#question').val();
            var result = "<p>Username: </p>" + username + " <br /><br /> " + 
            "<p>Question: </p>" + question + " <br /> <br /> ";
            console.log("Values of inputfield & textarea: " + result);

            //makes the connection to the server and send the data 
            var socket = io.connect('http://localhost:3000');
            socket.emit('sendQuestion', result);
            console.log("Gets send: " +result);
            //alert('test');
        });

        //returns the updated data + visualize it on the page
        socket.on('updateQuestion', function (data) 
        {
            console.log("Updated data: " + data);//data is the username and question = result
            $('#answer').css("border", "4px solid #9C27B0");
            $('#answer').css("borderRadius", "8px");
            $('#answer').css("padding", "10px");
            $('#answer').css("fontSize", "16px");
            $('#answer').append('<li>'+data+'</li>');
        }); 
    });
</script>

在我的 bin>www 文件中,我有以下用于服务器端连接的代码:

var io = require('socket.io')(server);
io.on('connection', function (socket) 
{
   socket.on('sendQuestion', function (data) 
  {
     console.log("The server received a question");
     console.log(data);

    // send question to ALL clients
    io.sockets.emit("updateQuestion", data.result);
  });
});

在chrome浏览器中我运行开发者工具和输出是下面的截图: http://www.nappdev.be/clientside.png

这是记录数据的服务器端的屏幕截图 http://www.nappdev.be/serverside.png

我希望有人能帮助我,因为我不明白为什么它返回 null

提前致谢!!1

[已编辑:刚刚注意到您实际上发送的是 data.result,它首先是 null]

发送 data.result 而不是发送 data

请注意,这将为您提供整个字符串(用户名 + 问题)。如果您只想要问题,则必须在服务器端解析接收到的字符串并仅将问题发送给连接的客户端。