June March
June March

Reputation: 13

Node + Express, pass array to client on page load?

I'm using Node + Express. On page load, the app calls a remote database, gets data and sends it to a handlebars template. All this is done server side. But I'd like to be able to have this same JSON data be available for the client to interact with. How do I do that?

Example, server displays a table of ten records. I want the client to be able to click on one record and get a details view of just that one record. Thanks.

Here's the code:

app.get('/', function(req, res) {
getDataFromDatabase(function(data) {
    data = JSON.parse(data);
    res.render('index', {
        stuff: data
    });
});

});

function getDataFromDatabase(callback) {

var options = {
    hostname: this.hostname,
    path: this.path,
    port: 80,
    method: 'GET'
}

http.request(url, function(res) {
    var data = '';
    res.on('data', function(chunk) {
        data += chunk;
    }).on('end', function() {
        callback(data);
    }).on('error', function() {
        console.log("error");
    })
}).end()

}

Upvotes: 0

Views: 1697

Answers (1)

Nocturno
Nocturno

Reputation: 10027

How do you get the data as a variable accessible to the client, on page load, when the server is doing all of the work? Do you have to make a redundant call from the client and get a "copy" of the data? - June March

If you don't want to make an AJAX call after the page loads to get at the data, you can send it along with the rest of the page inside of a script tag. Not sure which template engine you're using so the following is sudo code (might be Jade, I don't know). Do something like this in your template:

script var data = JSON.stringify(stuff); // <- horrible variable name btw

If you can successfully create a script tag in your template, and initialize a variable with the data you want to pass to the client, you shouldn't have to make another call to the server.

Upvotes: 1

Related Questions