Reputation: 1
I've got this little piece of code:
'use strict';
module.exports = MainCtrl;
function MainCtrl() {
this.defaultUrl = 'http://foo/';
}
MainCtrl.prototype.getPoi = function getPoi() {
request( 'http://foo/',function(error,response,body) {
console.log( body );
});
};
and on my route file I require like this:
var express = require('express');
var request = require('request');
var main_lib = require('../lib/main_ctrl.js');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
router.get('/newroute', function(req,res) {
//var mainCtrl = new main_lib.MainCtrl();
main_lib.getPoi();
res.render('newroute', { title: 'New Route' });
})
module.exports = router;
As you can see is very simple, I'm on my first steps with ExpressJS and NodeJS but I don't know why I've got this error:
TypeError: Object function MainCtrl() { this.defaultUrl = 'http://foo/'; } has no method 'getPoi'
I've look at the definition of the view module on express lib and is the same as:
module.exports = View;
function View(name, options) { .. }
View.prototype.lookup = function lookup(name) { .. }
But I can't understand what I'm doing wrong.
Upvotes: 0
Views: 1057
Reputation: 23816
You are getting error for calling function of MainCtrl
you need to create object of this class.
Use following code
'use strict';
function MainCtrl() {
this.defaultUrl = 'http://foo/';
}
MainCtrl.prototype.getPoi = function getPoi() {
request( 'http://foo/',function(error,response,body) {
console.log( body );
});
};
//added function for getting instance
module.exports.getInstance = function () {
return new MainCtrl();
};
While adding controller in router use this:
var main_lib = require('../lib/main_ctrl.js').getInstance();
Now main_lib
is object of your controller. So you can call like:
main_lib.getPoi();
If you want to use like View
module then manually you have to create object for this. like
'use strict';
module.exports = MainCtrl;
function MainCtrl() {
this.defaultUrl = 'http://foo/';
}
MainCtrl.prototype.getPoi = function getPoi() {
request( 'http://foo/',function(error,response,body) {
console.log( body );
});
};
In route file:
var main_lib = require('../lib/main_ctrl.js');
var main_lib_object = new main_lib();//take a look here
main_lib_object.getPoi(parameter);
Upvotes: 1