我是node,express,mongodb和socket.io的新手。事情一直很顺利,直到现在。所以我正在构建这个小测试应用程序,用户输入他的名字,然后发一个问题。
socket.io接收数据(用户名和问题)但返回时数据为空。 (一开始它正在工作,但后来我开始安装mongoose,从那时起事情就出错了)。我使用快速框架并安装了所有必要的模块。
在我的视图中,这是连接套接字和更新数据的代码:
<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&gt; 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
答案 0 :(得分:0)
[编辑:刚刚注意到你实际上发送的data.result
首先是空的]
而不是发送data.result
发送data
。
请注意,这将为您提供整个字符串(用户名+问题)。如果您只想要问题,则必须在服务器端解析收到的字符串,并仅向连接的客户端发出问题。