Shuyinsama Shuyinsama - 3 months ago 26
reST (reStructuredText) Question

Send REST response to Handlebars to parse JSON

So i've recently took the jump to node based web apps (I've been playing around with a lot a lot but now I'm actually creating something)

So i've set up a simple REST API using Express, MongoDB and Node (published on Heroku)
Now I am trying to create a client/web app also in Express and Node that communicates with the API and parses the responses and actually views the object.

What I want to do is list the current entries of the API on a simple page.
So i've created a route to '/home' in my app that works fine.
It uses a handlebars template that works fine too.

I use a 'home.js' file to render the view like so:

var request = require('request');
exports.index = function (req, res) {
res.render('home', {
title: 'home'
});
};


I've tried different things here but whenever I do something like:

var request = require('request');

exports.index = function (req, res) {
res.render('home', {
title: 'home',
items: getItems
});
};

var getItems = function(req, res, next) {
request(process.env.API_URL, function(err, resp, body) {
if (!err && resp.statusCode == 200) {
return body;
}
}
};


It returns the
request
object/function instead of the body (which I can parse in handlebars :P)

I did numerous variations on this call (calling it within the
exporst.index
functions, outside of it, creating a options variable and a seperate callback like
request(options, callback)
) but they all either error or return the
request
object/function.

When I do
console.log(body);
instead of
return body;
it does log correctly.

I am kind of running in circles now I guess.

Many thanks for any help :)

Answer

You are referencing the function getItems when calling res.render instead of executing the function, getting the output and assigning it to items.

res.render('home', {
       title: 'home',
       items: getItems // this is just a reference to "getItems" function.
   });

You need to execute the function getItems to get the actual data and render it in the view.

For flow control: You can wrap getItems in a promise and use co-express to yield the promise in a route handler.

Comments