Passing a var from server to client

1.5k views Asked by At

I'm using node.js + Express + EJS.

In my route, I'm accessing an external API to get some data:

router.get('/', function(req, res, next) {

var request = https.get(url + 'products.json', function(response){
    var buffer = "", 
    route;

    response.on("data", function (chunk) {
        buffer += chunk;
    }); 

    response.on("end", function (err) {
    // finished transferring data
    // dump the raw data
    console.log(buffer);
    console.log("\n");
    data = JSON.parse(buffer);
    route = data;

    }); 
});

res.render('index', { 
    title: 'Home',
    products: JSON.stringify(data)

});
});
exports.router = router;
exports.products = data;

My goal is to pass this data variable to the client side. In my app.js file I set -

app.locals.productsData = routes.products;

In my index.ejs file this is what I'm trying to do -

 <script>
var products = <%= products %>;
</script>

or stuff like

    <script>
        var products = <%= {{productsData}} %>;
    </script> 

I can't seem to find a way to pass this data.

Can you help me out please?

1

There are 1 answers

3
Jerome WAGNER On BEST ANSWER

You are calling res.render in the wrong place (data will only have its value later, when request will send its end event.

So you need to move the res.render inside the end event callback.

Try

response.on("end", function (err) {
    // finished transferring data
    // dump the raw data
    var data = JSON.parse(buffer);
    res.render('index', { 
      title: 'Home',
      products: JSON.stringify(data)
    });
}); 

with

<script>
var products = "<%= products %>";
</script>