I am getting error while i am trying to loop through a json object. I am getting data from api and pass it to view.I tried to print the whole object their is no issue. If i try to loop trough , it is throwing error. But if i hardcode the response in controller( whatever response come from api ) it is working fine.
this is controller with hardcoded response
module.exports = {
index: function(req, res) {
var request = require("request");
request("http://app.coreosadmin.com/emp.json", function(error, response, body) {
if (error) {
console.log(error);
} else {
var menuData=[{"id":"Dasboard","icon":""},
{"id":"Subscriptions","icon":""},
{"id":"Extensions","icon":""},
{"id":"Adds Management","icon":""},
{"id":"Client Management","icon":""},
{"id":"User Management","icon":""},
{"id":"Settings","icon":""},
{"id":"Enums","icon":""},
{"id":"Accounts","icon":""},
{"id":"Reports","icon":""}];
return res.view('homepage',{menus:menuData});
}
});
}
};
This is my controller
module.exports = {
index: function (req, res) {
var request = require("request");
request("http://someurl.com/emp.json", function(error, response, body) {
if (error) {
console.log(error);
} else {
return res.view('homepage',{menus:body});
}
});
}
};
this is my home view
<div class="menu_section">
<ul>
<% menus.forEach(function(menu) { %>
<li title="<%- menu.id %>">
<a href="index.html">
<span class="menu_title"><%- menu.id %></span>
</a>
</li>
<% }); %>
</ul>
</div>
Its solved. i had to use JSON.parse .
return res.view('homepage',{menus:JSON.parse(body)});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With