简体   繁体   English

我如何在node.js中将数组从服务器端传输到客户端?

[英]How do I get to transfer an array from the server side to client side in node.js?

I have the following function on the client side: 我在客户端具有以下功能:

                //TODO: to fix
                var socket = io.connect('http://localhost:3000/home');
                socket.on('news', function (data) {
                    console.log('testing: ' + data);
                    //socket.emit('my other event', {my: 'data'});
                });

And the following on the server side: 以及服务器端的以下内容:

module.exports = function(app, io) {

    app.get('/home',function(req, res){
        //res.render('profile.ejs');
    });
    io.on('connection', function(socket){
        socket.emit('news', {
        data: 'world'
        });
};

The problem is that I can't seem to log the received data to the client's console. 问题是我似乎无法将收到的数据记录到客户端的控制台。 What's wrong with my code? 我的代码有什么问题?

使用JSON.stringify()以适当的格式打印整个数据

console.log('testing: ' + JSON.stringify(data));

By calling console.log('testing: ' + data); 通过调用console.log('testing: ' + data); , Javascript is trying to convert the object data to a string, by calling toString . ,Javascript试图通过调用toString将对象data转换为字符串。 This will result in the string "testing: [object Object]". 这将导致字符串“ testing:[object Object]”。

You need to either manually convert the object to a more useful string, eg by calling JSON.stringify(data) , or you can make use of the feature that console.log may receive multiple arguments: 您需要手动将对象转换为更有用的字符串,例如通过调用JSON.stringify(data) ,或者可以利用console.log可能接收多个参数的功能:

console.log('testing:', data);

This way your console is printing the acutall object and not a string representation. 这样,您的控制台将打印acutall对象而不是字符串表示形式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM