如何摆脱这个Node.js聊天中的“未定义”

时间:2016-09-21 13:58:39

标签: javascript node.js sockets socket.io

我是Node.js和Socket.IO的新手,我似乎无法弄清楚为什么我会继续“未定义”,我正试图在消息前面获取用户名,但是我似乎无法摆脱那种讨厌的未定义。

这是我的index.js

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);


app.get('/', function(req, res){
  res.sendfile('index.html');
});

io.on('connection', function(socket){
  console.log('a user connected');
  io.emit('chat message','User Connected');
  socket.on('disconnect', function(){
  io.emit('chat message','User Disconnected');
    console.log('user disconnected');
  });
});

http.listen(13280, function(){
  console.log('listening on *:13280');
});

io.on('connection', function(socket){
  socket.on('chat message', function(msg){
    console.log('message: ' + msg);
  });
});

io.on('connection', function(socket){
  socket.on('chat message', function(msg,username){
    io.emit('chat message',username + msg);
  });
});

和我的index.html

<!doctype html>
<html>
  <head>
    <title>Socket.IO chat</title>
    <style>
      * { margin: 0; padding: 0; box-sizing: border-box; }
      body { font: 13px Helvetica, Arial; }
      form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
      form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; }
      form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
      .name {margin-bottom: 40px;}
      #messages { list-style-type: none; margin: 0; padding: 0; }
      #messages li { padding: 5px 10px; }
      #messages li:nth-child(odd) { background: #eee; }
    </style>
  </head>  
<body>
    <ul id="messages"></ul>
    <form action="">
      <input id="m" autocomplete="off" /><button>Send</button>
    </form>

        <script src="/socket.io/socket.io.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script>
var name = prompt("Choose a username","username");
var halveusername = "[" + name;
var username = halveusername + "] ";
var socket = io();

  $('form').submit(function(){
    socket.emit('chat message',username + $('#m').val());
    $('#m').val('');
    return false;
  });

  socket.on('chat message', function(msg){
    $('#messages').append($('<li>').text(msg));
  });

</script>
  </body>
</html>

1 个答案:

答案 0 :(得分:0)

如果它包含多个值,你可能最好将json对象作为消息发送 - 它为您提供了更大的灵活性,并且无论如何都会修复您的错误。

试试这个

  index.js中的

io.on('connection', function(socket){
  socket.on('chat message', function(message){
    io.emit('chat message', message);
  });
});
  

和index.html

$('form').submit(function(){

    var message = {
        username: username,
        text: $('#m').val()
    };

    socket.emit('chat message', message);
    $('#m').val('');
    return false;
});

socket.on('chat message', function(msg){
    $('#messages').append($('<li>').text(msg.username + msg.text));
 });