将数据从服务器端发送到客户端节点

时间:2018-02-11 15:37:51

标签: javascript jquery node.js server-side

服务器端:App.js:

const express = require('express')
const app = express()
var fire = require('./Firebase.js')

app.get('/route', function (req, res) {
    fire.getData(req.body, res)
})

服务器端:Firebase.js

var firebase = require('firebase')
firebase.initializeApp(config);
var v = firebase.database();

var users = firebase.database().ref("users");

exports.getData = function(data, res){
    users.once('value', function(snapshot) {
        snapshot.forEach(function(childSnapshot) {

        var childData = childSnapshot.val();
   //Solution: Array if more values than one.

        var content = '';
        content += '<tr>';
        content +='<td>'+ childData.Firstname + '<td>';
        content +='<td>'+ childData.Lastname + '<td>';
        content += '</tr>';
        res.send(content);
        });
    });   
}

客户端:Structure.js

$.get("/route", function (response) { 
    console.log(response)
}) 

但问题是,它说我试图两次调用它,向我发送不同的错误消息。那么如何从服务器端到客户端获取价值呢?它在Firebase.js和App.js中显示正确的数据whild console.log(...)。我发现了一些帖子如何做到这一点,但它并不适合我的问题。 解决方案:转换两次或更多次,因为我没有从firebase中折叠值的数组。

1 个答案:

答案 0 :(得分:1)

您无法在服务器端附加数据,这意味着 你不能在服务器上这样做 $('#valuesFromDatabase').append(content);

相反,您应该在客户端上执行此操作:

$.get("/route", function (response) {
    console.log(response)
    $('#valuesFromDatabase').append(response);
    //Code here trying to print out to a table with the id                           
    'valuesFromDatabase' 
})