Reputation: 804
I am fairly new to NodeJS and asynchronous programming. I've never been seriously into JavaScript until I started working on a project that required me to set up a REST API using node server and I started working on it for the past day or two. I'm trying to set up a modular application and have been successful in setting up a route, model and controller using Express JS.
I use express to read the request bodies to get data posted to the server in JSON. But my current situation came up when I tried to pass certain data from my routes module (or file) to my controller in a function call.
When I couldn't read the data I tried to log it and to my surprise the JSON Object that I passed as an argument is now logged as a [Function].
Here is how I pass the data:
routes.js
var express = require('express');
var UserCtrl = require('./controller');
var user = express.Router();
// Define routes
// Request to list all users.
user.get('/', function (req, res){
UserCtrl.getAll(function (result){
res.json(result);
});
});
user.post('/create', function (req, res){
var postData = {
'firstName': req.body.firstName
};
UserCtrl.create(function (postData, result){
res.json(result);
});
});
module.exports = user;
controller.js
var Users = require('./model');
// list all users
module.exports.getAll = function (callback) {
Users.findAll(callback);
}
// create user
module.exports.create = function (postData, callback) {
console.log(postData);
// create user by passing the user to a model
Users.create (newUser, callback);
}
May be I've got the basics wrong or may be this is completely a mistake of my code. Should I make the controller also an express middleware?
Upvotes: 0
Views: 36
Reputation: 1995
This code calls create. The first value sent to it is a function. This function that you send to create takes in a postData
and a result
value.
UserCtrl.create(function (postData, result){
res.json(result);
});
This code is what is getting called. The first thing that gets sent in is postData. When you called it just above you sent in a function to that first thing. So console.log will output function.
module.exports.create = function (postData, callback) {
console.log(postData);
// create user by passing the user to a model
Users.create (newUser, callback);
}
Perhaps you meant to send in that postData object first?
user.post('/create', function (req, res){
var postData = {
'firstName': req.body.firstName
};
// This is the changed line
UserCtrl.create(postData, function (postData, result){
res.json(result);
});
});
Upvotes: 1