Node JS and custom module with express js - javascript

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.

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);

Related

express.js router unit testing error

I have a node/express application with a controller and service. While running the unit test for controller via Grunt/Jasmine, the test runs fine but after the coverage summary I get the following error:
error: Error on SAVE state TypeError: Cannot read property 'apply' of undefined
at /node_modules/express/lib/router/index.js:603:14
at next (/node_modules/express/lib/router/index.js:246:14)
at next (/node_modules/express/lib/router/route.js:100:14)
Controller.js
var express = require('express'),
router = express.Router();
module.exports = function(app) {
app.use('/api', router);
router.post('/save', function(req, res, next) {
// Service code is invoked here with the success/error callback
// on success - res.json(response);
// on error - res.status(err.status);
});
}
ControllerSpec.js
var app = require('../mockApp'); // the app.js and the express app is mocked here
var httpMocks = require('node-mocks-http');
var request = require('request');
describe("Controller SAVE Action", function () {
it("With Error", function () {
spyOn(service, "save").andCallFake(function (req, res, headers, callback) {
callback({category: "Error"});
});
var rout = app.getRouter("/state"); // the mocked app.js contains a getRouter function which returns the corresponding router which is simply express.Router()
var request = httpMocks.createRequest({
method: 'POST',
url: '/save',
headers: {"authorization": "success"}
});
var response = httpMocks.createResponse();
rout(request, response);
var data = JSON.parse(response._getData());
expect(data.code).toEqual(400);
});
});
Mocked app.js
var m = {};
var routers = {};
module.exports = {
get: function (name) {
return m[name];
}, set: function (name, obj) {
m[name] = obj;
}, use: function (path, router) {
if (router) {
routers[path] = router;
}
}, getRouter: function (path) {
return routers[path];
}
};
Mocked Express.js
var app = require('./app'); // Mocked app.js
var services = {};
var serviceFiles = glob.sync(rootPath + '/app/services/*.js');
serviceFiles.forEach(function (file) {
var service = require(file)(app);
services[service.serviceName] = service;
});
app.set("services", services);
var controllers = glob.sync(rootPath + '/app/controllers/*.js');
controllers.forEach(function (controller) {
require(controller)(app);
});

Backbone route with push state not working on page refresh

var Backbone = require('backbone'),
SellerProfileView = require('./views/seller/SellerProfileView');
var Router = Backbone.Router.extend({
routes: {
":user_name" : "sellerProfile"
},
sellerProfile: function (username) {
"use strict";
var sellerProfile = new SellerProfileView({username: username});
}
});
module.exports = Router
var Router = require('./router'),
Backbone = require('backbone'),
$ = require('jquery');
var app = {
init: function () {
"use strict";
Backbone.$ = $;
this.router = new Router();
$(document).ready(function () {
Backbone.history.start({ pushState: true, route: '/' });
});
}
};
module.exports = app;
app.init();
I get the below error if i refresh the page without the hash
Error response
Error code 404.
Message: File not found.
Error code explanation: 404 = Nothing matches the given URI.
Please help.
pushState will try to load the ressource.And it seems your server is not loading anything at 'yourwebsiteurl.com/'

Why do I get 'undefined is not a function'?

I'm trying to return a file as a response to a GET request using express.js
I wrote a simple FileManager class to handle file request, however i'm getting the 'undefined is not a function' error ,when I call new FileManager()
Here's, how I try to do this:
//FileManager.js
FileManager = function () {}; //Empty initializer
FileManager.prototype.handleFileRequest = function(req,res){
var fileId = req.params.id
if(fileId){
var path = './uploads/events' + fileId;
res.sendfile(path)
} else {
res.send(404, 'file not found')
}
}
Here's the server:
//server.js
var express = require('express');
var FileManager = require('./FileManager.js').FileManager;
var app = express();
var fileman = new FileManager();
app.get('/:id', function (req, res){
console.log('get id:' + req.params.id);
fileman.handleFileRequest(req,res);
})
app.listen('blabla',3000);
but when I run node server.js , i get the following error:
var fileman = new FileManager();
^
TypeError: undefined is not a function
In FileManager.js ... you need to export the object.
module.exports = {
FileManager : FileManager
}
server.js
var FileManager = require('./FileManager.js').FileManager;
// this has the FileManager object that was created in the FileManager.js

How export a module in node.js

emailConfirmation.js:
var configAuth = require('../../authentication/sendgrid');
var sendgrid = require('sendgrid')(configAuth.sg.username, configAuth.sg.password);
var from_address = "mycompany#pubcrawlsp.com";
var text_body = "sometextbody";
var html_body = "somehtml";
Them i need export in my routes, to use in a post route, like this:
app.post('/', function(req, res) {
sendgrid.send({
to: req.body.email,
from: the from_adrres variable from the other file,
subject: "Some subjec",
text: the text_body variable from the other file
html: the html_body variable from the other file
}, function(err, json) {
if (err) {
return console.error(err);
}
console.log(json);
});
});
How can i export the emailConfirmation.js and use like that??
Start by creating a file just for your code.
At the end of the file, you would "expose" parts of the code to a consumer. For example:
In your case you could wrap your code like so:
module.exports.set = function(app) {
app.post('/', function(req, res) {
/* the post code goes here */
});
};
You could consume it with app.js like so on app.js:
require('./sendgrid').set(app);
This would effectively set your route(s) for sendgrid.

How to get a variable defined in index.js from within a controller?

I'm testing forms-angular (http://www.forms-angular.org/).
I define a DataFormHandler variable in my index.js file. And also I need to get this variable in my controllers. How may I get it? This setter doesn't work app.set("formHandler", DataFormHandler).
Here is the code:
index.js
'use strict';
var formsAngular = require('forms-angular'); // require formsAngular
var kraken = require('kraken-js'),
app = require('express')(),
options = {
onconfig: function (config, next) {
//any config setup/overrides here
next(null, config);
}
},
port = process.env.PORT || 8000;
// Here I initialize FormHandler. It requires the app, so I initialize it here, in index.js
// HOW TO GET THIS VAR IN CONTROLLERS?
var DataFormHandler = new (formsAngular)(app);
app.set("fh", DataFormHandler); // THIS DOESN'T WORK. UNDEFINED in controller
app.use(kraken(options));
app.listen(port, function (err) {
console.log('[%s] Listening on http://localhost:%d', app.settings.env, port);
});
The setter app.set("fh", DataFormHandler) doesn't work. When I try to get fh from within a controller it is undefined:
app\controllers\index.js
'use strict';
var UserModel = require('../models/user');
module.exports = function (router) {
var user = new UserModel();
router.get('/', function (req, res) {
var DataFormHandler = req.app.get("fh");
DataFormHandler.addResource('user', UserModel);
console.log("DataFormHandler", DataFormHandler); // undefined
var model = {
hello: "Hello"
}
res.render('index', model);
});
};
How to get a variable in a controller?
I found one solution that works. But not sure that it's the correct one.
Instead of
app.set(key, value)
which doesn't work, I use
app.locals.key = value
that for some reason works.

Categories

Resources