naga muru naga muru - 12 days ago 8
Node.js Question

socket io not parse string and any characters

I want send simple message to node.js console from html. But number is working , string and any characters not working,
Display message is
message: NaN

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendFile('sample.html', {
root:'/home/deneebo/Documents/apidevelopment/nodejs'});
});
io.on('connection', function(socket) {
socket.on('chat message', function(msg) {
console.log('message: ', + msg);});
});
http.listen(3000, function(){
console.log('listening on *:3000');
});


below html code

<!doctype html>
<html>
<head>
<title>Socket.IO chat</title>

</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 socket = io();
$('form').submit(function(){
socket.emit('chat message', $('#m').val());
alert($('#m').val());
$('#m').val('');

return false;
});
</script>
</body>

</html>

Answer

I tried your code my local work well

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

var io = require('socket.io')(http);

app.get('/', function(req, res){

  res.sendfile('stack.html', {root: __dirname });
});
io.on('connection', function(socket) {
    socket.on('chat message', function(msg) {
        console.log('message: ',  msg);}); //Remove + from here
});
http.listen(3000, function(){
    console.log('listening on *:3000');
});

enter image description here