Express.js - export/access function within route file - node.js

I am trying to export function within route file. Here is my code
app.js file
var express = require('express');
var bodyParser = require('body-parser');
var users = require('./routes/users');
var others=require('./routes/others')
var app = express();
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/others', others);
app.use('/users', users);
module.exports = app;
others.js file
var express = require('express');
var router = express.Router();
router.post("/test", function (req, res, next) {
res.send("success");
});
//Here i want to export function to users js file
var funDef=function(){
console.log("export a function")
}
moudle.exports=router;
How can I export or call funDef in users.js file. I tried the following way but it is not working
users.js file
var express = require('express');
var router = express.Router();
var readFun= require("./others.js");
router.post("/testUsers", function (req, res, next) {
res.send("suceess");
});
//getting undefined
readFun.funDef();
module.exports=router;
Can anyone guide me?

Try for the following:
function router() {}
router.prototype.funDef=function(){
console.log("export a function")
}
moudle.exports.router=router;
Another file:
var router = require('router').router;
var Router = new router();
Router.funDef();
EDIT:
// module.js
'use strict';
var temp = "this is a test";
module.exports.func = function() {
return temp;
}
// app.js
'use strict';
var module = require('./module');
console.log(module.func());

Related

Expressjs - TypeError: Cannot read property 'apply' of undefined

I know there are other questions about this error, but none of them helped me. Everything was working fine untill I decided to add consign and change my directories structure.
I tried changing the orders my route is being loaded, but did not work
This is server.js:
'use strict';
const express = require('express');
const consign = require('consign');
const path = require('path');
const cookieParser = require('cookie-parser');
const porta = 3000;
const app = express();
const pathFront = '../app/front/';
//app.use(require('../app/routes/'));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, pathFront + 'public')));
app.set('views', path.join(__dirname, pathFront + 'views'));
app.set('view engine', 'pug');
app.use(require('../app/routes/')); // still not working
// Tried to change the include order, did not work
consign()
.include('./app/routes')
.then('./config/db.js')
.then('./app/back/api/models')
.then('./app/back/api/controllers')
.into(app);
module.exports = app;
This is route index:
'use strict';
var express = require('express');
var router = express.Router();
router.get('/', function(req, res, next) {
res.render('index', { title: 'API' });
});
/* ENDPOINTS*/
/*
/languages -- all
/language?idLanguage
/language?name=
/languages?idCategory
/language?name=
/categories
//
*/
module.exports = router;
This is folder structure:
And running npm start:
Going by your sample code, you don't seem to be using consign correctly. The included files (using .include or .then there after) should export one function which takes the express app as parameter. Check this example in consign repo. Functions from each of the included file is called with the object which you provide to .into(). You can very well let go of consign, and manually require and use each fo the files, which seems to be working as per your comments.
Otherwise you can change your routes files to something like this:
server.js doesn't change.
app/routes/index.js changes to following:
'use strict';
var express = require('express');
var router = express.Router();
router.get('/', function(req, res, next) {
res.render('index', { title: 'API' });
});
/* ENDPOINTS*/
/*
/languages -- all
/language?idLanguage
/language?name=
/languages?idCategory
/language?name=
/categories
//
*/
module.exports = function (app) {
app.use('/', router);
}
Followed by similar changes in all other files that you'd use with consign.

router redirect in express not working

I have 3 files
app
routes/index.js
routes/home.js
app.js
var express = require('express');
var app = express();
//require routes
var index = require('./routes/index.js')
var home = require('./routes/home.js')
app.set('port',3000)
app.set('view engine', 'pug')
app.use('/', index);
app.use('/home' , home);
//app.use('/routes',users);
app.listen(3000);
module.exports = app;
index.js
var express = require('express');
var router = express.Router();
router.get('/' , function(req,res){
res.redirect('/home')
})
module.exports = router;
home.js
var express = require('express');
var router = express.Router();
router.get('/home' , function(req ,res){
res.send('Got request on home route')
})
module.exports = router;
This sends a cannot GET on HOME route.Strangely this works if i put both routes in one file.I think I am making a mistake while importing?

Routing folders with express in node.js

I decided to take my routes out of my app.js and into their own seperate folders but now the site will load the handlebars file for index but not for about or contact - I am very confused and require help in exchange for a +1.
// Import the express module
var express = require('express');
var path = require("path");
var bodyParser = require("body-parser");
var index = require('./routes/index');
var about = require('./routes/about');
var contact = require('./routes/contact');
var handlebars = require('express-handlebars').create({defaultLayout:'main'});
var app = express();
// Block the header from containing information
// about the server
app.disable('x-powered-by');
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'handlebars');
app.engine('handlebars', handlebars.engine);
//set static folder
app.use(express.static(__dirname + '/public'));//allows access to public directory
//set bower folder
app.use('/bower_components', express.static(__dirname + '/bower_components'));//defines bower components directory
//body parser MW
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.set('port', process.env.PORT || 1337);// Defines the port to run on
app.use("/", index);
app.use("/about", about);
app.use("/contact", contact);
app.use(function(req, res){
res.type('text/html');
res.status(404);
res.render('404');
});
app.use(function(err, req, res, next){
console.error(err.stack);
res.status(500);
res.render('500');
});
app.listen(app.get('port'), function(){
console.log("Express started on http://127.0.0.1:" + app.get('port') + ' Press Ctrl+C to terminate');
})
This is the routes/index.js file:
var express = require("express");
var router = express.Router();
// Defines the base url
router.get('/', function(req, res, next){
// Point at the home.handlebars view
res.render('home');
});
module.exports = router;
And routes/about.js
var express = require("express");
var router = express.Router();
router.get('/about', function(req, res, next){
res.render('about');
});
module.exports = router;
When I go to localhost/contact, I get my 404 page and the same for /about.
The views are located in app/views, it worked when I had them down the pipeline in the app.js but since removing them it has broken. Any suggestions would be much appreciated!
This issue was with the routing itself. Say we are looking for /about with:
app.use("/about", about);
The app will then look into the routing folder of about and find the following.
var express = require("express");
var router = express.Router();
router.get('/about', function(req, res, next){
res.render('about');
});
module.exports = router;
And since I had another /about here in the router.get this would render at localhost/about/about

Getting invalid URL message in expressjs code

I am new to express.js coding. In my code below i want to access two URLs like http://localhost:3000 and http://localhost:3000/fetch to serve different requests using get method. While accessing the first URL i am able to get the response but while accessing second URL i am getting 404 error. I am unable to figure out the issue, can you please help me out in this.
Below are my files:
app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var index = require('./routes/index');
var fetch = require('./routes/fetch');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.use('/fetch',fetch);
app.use('/', index);
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('SmartBin: Invalid URL');
err.status = 404;
next(err);
});
modules.export=app;
index.js
var express = require('express');
/* GET home page */
module.exports = (function() {
var path = require('path');
var bodyParser = require('body-parser');
var db = require('./dbclient');
db.dbconnection(null,null,null,null,'smartbin',null);
var router = express.Router();
router.get('/', function(req, res, next) {
//res.render('index', { title: 'Express' });
db.get('devicereg',{}).then(function(v){
//for (i=0; i<v.length-1; i++)
//res.json(v[i]);
res.json(v);//.end();
}).catch(function(v){
console.log('[SmartBin:Error ' + v);
});
});
return router;
})();
fetch.js
var express = require('express');
/* GET home page. */
module.exports = (function(){
var path = require('path');
var bodyParser = require('body-parser');
var router = express.Router();
var db = require('./dbclient');
db.dbconnection(null,null,null,null,'smartbin',null);
router.get('/fetch', function(req, res, next) {
db.get('devicereg',{}).then(function(v){
res.json(v);
}).catch(function(v)
{console.log('[SmartBin:Error ' + v);}
);
});
return router;
})();
I think you could try one of these options:
1. Minor changes:
In your app.js use the app.use('/', index) and app.use('/', 'fetch'). Your route is set inside the index.js and fetch.js files, so it should work, even not having in your app.js the code app.use('/fetch', 'fetch').
In your existing code you probably can access http://localhost:3000/fetch/fetch (because you are declaring /fetch in app.js and then declaring again /fetch in fetch.js file).
2. Pass app by parameter to the route file:
In your app.js, try to require your route files passing your instance of app, instead of app.use('/', index) and app.use('/fetch', fetch).
E.g.:
app.js
var express = require('express');
var app = express();
// Comment these lines
//app.use('/fetch',fetch);
//app.use('/', index);
// Add this lines passing the instance of 'app' you've created
var indexRoute = require('./routes/index')(app)
var indexFetch = require('./routes/fetch')(app)
In your route files, try to adapt as the following:
index.js
module.exports = function(app) {
app.get('/', function(req, res) {
res.send("This is index");
});
}
fetch
module.exports = function(app) {
app.get('/fetch', function(req, res) {
res.send("This is fetch");
});
}
Hope it helps.

How to move route function to another js file in express.js?

I have the following code (app.js):
var express = require('express');
var bodyParser = require('body-parser');
var mongoskin = require('mongoskin');
var routes = require('./routes/index');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
var db = mongoskin.db('mongodb://#localhost:27017/testdb', {safe:true})
app.param('orders', function(req, res, next, collectionName){
req.collection = db.collection(collectionName)
return next()
})
app.use('/', routes);
app.get('/api/:orders', function(req, res, next) {
req.collection.find({} ,{limit:10, sort: [['_id',-1]]}).toArray(function(e, results){
if (e) return next(e)
res.send(results)
})
})
Which works. What I'm going to do is to move the route (/api/:order) to another js file (routes/api.js). Here is the code:
var express = require('express');
var bodyParser = require('body-parser');
var mongoskin = require('mongoskin');
var routes = require('./routes/index');
var api = require('./routes/api');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
var db = mongoskin.db('mongodb://#localhost:27017/testdb', {safe:true})
app.param('orders', function(req, res, next, collectionName){
req.collection = db.collection(collectionName)
return next()
})
app.use('/', routes);
app.use('/api', api);
The /routes/api.js file:
var express = require('express');
var router = express.Router();
router.get('/', function(req, res) {
res.send('respond with a resource');
});
// return all orders
router.get('/:orders', function(req, res, next) {
req.collection.find({} ,{limit:10, sort: [['_id',-1]]}).toArray(function(e, results){
if (e) return next(e)
res.send(results)
})
})
module.exports = router;
I got the following error:
TypeError: Cannot call method 'find' of undefined
Can anybody tell me what's wrong with my code? Thanks.
I assume req.collection is undefined, because app.param('orders') is not executed for the other router.

Resources