I'm working with Express, Hoganjs, Nodejs.
The code below keeps returning "500 TypeError: Cannot call method 'json' of undefined"
I figure there is something wrong with how I am calling getUsers, but I'm too much of a newbie to figure it out. None of the tutorials or forums I have referred to are helping as of yet.
exports.admin = function(req, res){
getUsers(function(error, res){
res.render('admin', {
title: 'Admin',
userlist: res
});
});
};
function getUsers(req, res) {
res.json([
{username: "fake", permission: "admin" },
{username: "fake2", permission: "user" }
])
}
exports.getUsers = getUsers;
OK, so your code snippet is not properly formatted and thus hard to read, but I think exports.admin is being called as an express route that takes req, res. So far so good. Then you call getUsers and pass it a callback, but getUsers doesn't take a callback, it takes req, res as well. It's unclear what you're trying to do, but something like this would be reasonable:
exports.admin = function(req, res) {
loadUsers(function (error, users) {
if (error) {
return res.status(500).send(error);
}
res.render('admin', {
title: 'Admin',
userlist: users
});
}
};
exports.getUsers = function(req, res) {
loadUsers(function (error, users) {
if (error) {
return res.status(500).send(error);
}
res.send(users);
});
}
function loadUsers(callback) {
process.nextTick(function () {
callback(null, [
{username: "fake", permission: "admin" },
{username: "fake2", permission: "user" }]
);
});
}
An even better pattern would be to code loadUsers as middleware, FYI.