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?
You are calling
res.render
in the wrong place (data will only have its value later, whenrequest
will send itsend
event.So you need to move the
res.render
inside theend
event callback.Try
with