开发者

cannot display my variable on browser

I am working on a sock开发者_如何转开发et.io + Node.js project.

When I print an variable using console.log, I get my variable on console. But when I sent this variable to a client, it seems as [object Object] form on browser. How can I see my variable on browser?

Thanks


Try console.log(JSON.stringify(myVariable)); and then look at it in your browser and you'll gain more insight as to what's happening exactly.


You may be using the 0.6 serverside syntax of:

socket.send({foo: 'bar'})

Try using the following updated syntax:

socket.json.send({foo: 'bar'})

You can find more information here: https://github.com/LearnBoost/Socket.IO/wiki/Migrating-0.6-to-0.7


thanks, console.log(JSON.stringify(myVariable)); worked for my case. Variable has shown as { coloumn_that_result_lays: "result"}. Of course we can overcome it with javascript-substring but is there a function which gives "result" directly.

    // Require HTTP module (to start server) and Socket.IO
var  io = require('socket.io'),
http = require('http'); 
io = require('socket.io');
// Start the server at port 8080
var server = http.createServer(function(req, res){ 

    // Send HTML headers and message
    res.writeHead(200,{ 'Content-Type': 'text/html' }); 
    res.end('<h1>Hello Socket Lover!</h1>');
});
server.listen(8080);

// Create a Socket.IO instance, passing it our server
var socket = io.listen(server);

// Add a connect listener
socket.on('connection', function (client){ 
//mysql
var mysql = require('db-mysql');
new mysql.Database({
    hostname: 'localhost',
    user: 'root',
    password: '123123',
    database: 'node'
}).connect(function(error) {
    if (error) {
        return console.log('CONNECTION error: ' + error);
    }
    this.query('SELECT data FROM exam where id=2 ').
        execute(function(error,result) {
                if (error) {
                        console.log('ERROR: ' + error);
                        return;
                }
                client.json.send(JSON.stringify(result));


    });
});

    // Create periodical which ends a message to the client every 5 seconds
    var interval = setInterval(function() {
        client.send('This is a message from the server!  ' );


    },1000);

    // Success!  Now listen to messages to be received
    client.on('message',function(event){ 
        console.log('Received message from client!',event);
    });
    client.on('disconnect',function(){
        clearInterval(interval);
        console.log('Server has disconnected');
    });

});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜