I'm using Express 4.2.0
Is it possible to include a module only once in app.js and use it in any defined route?
Right now this won't work:
app.js
//..
var request = require('request');
var routes = require('./routes/index');
var users = require('./routes/users');
app.use('/', routes);
app.use('/users', users);
//...
routes/user.js
var express = require('express');
var router = express.Router();
router.get('/add', function(req, res) {
var session = req.session;
request('http://localhost:8181/Test?val1=getDepartments', function (error, response, body) {
//...
});
res.render('users/add');
});
module.exports = router;
It will say that "request" is not defined in routes/user.js
ReferenceError: request is not defined
at Object.module.exports [as handle] (C:\inetpub\wwwroot\node7\routes\users.
js:12:5)
Having to include modules in every route which wants to use them doesn't sound like a proper solution...
Yes, there are two ways of creating global variables in Node.js, one using the global object, and the other using module.exports
Here is how,
Method 1. Declare variable without var keyword. Just like importModName = require('modxyz') and it will be stored in global object so you can use it anywhere like global.importModName
Method 2. Using exports option.
var importModName = require('modxyz');
module.exports = importModName ; and you can use it in other modules.
Look here for somemore explanation http://www.hacksparrow.com/global-variables-in-node-js.html
You can leave out the var and do just request = require('request'); but this is frowned upon.
Node.js caches modules. The standard approach is to require modules where needed.
Related
Keep getting this error, whilst trying to run my app. Low level of knowledge have tried many solutions online to fix this, but nothing has got me up and running. Here is the Error-
Error: Route.get() requires a callback function but got a [object Undefined]
at Route.(anonymous function) [as get] (d:\dev_portal\bit_racer_real\alpha_bit_racer\node_modules\express\lib\router\route.js:202:15)
index.js
var express = require('express');
var router = express.Router();
router.get('/', function(req, res) {
res.redirect('/catalog');
});
module.exports = router;
catalog.js
var express = require('express');
var router = express.Router();
// Require controller modules.
var horse_controller = require('../controllers/horseController');
router.get('/', horse_controller.index);
module.exports = router;
app.js
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var catalogRouter = require('./routes/catalog');
var app = express();
var mongoose = require('mongoose');
var mongoDB = 'mongodb://admin:bitracer33#ds123753.mlab.com:23753/alpha_bit_racer';
mongoose.connect(mongoDB);
mongoose.Promise = global.Promise;
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/catalog', catalogRouter);
module.exports = app;
Not exactly sure where I have gone wrong, I have also heard that I may have a call in my routes index.js file in express. The call doesn't exist. I have spent hours going over the code making small changes, trying to get this simple error to clear :(
Has anyone else experienced this problem. Id love to get a clear answer.
as far as I can see, your index.js file is in the horsecontroller directory.
But when you use CommonJS's require with a directory instead of a file, it automatically defaults that to ../path/to/directory/index.js, so you don't have to specify horse_controller.index in the app.get function, instead just specify horse_controller.
The final code would look like this:
var express = require('express');
var router = express.Router();
// Require controller modules.
var horse_controller = require('../controllers/horseController');
router.get('/', horse_controller);
module.exports = router;
Like Daksh said, in the line router.get('/', horse_controller.index); (file catalog.js) horse_controller.index is not a function.
In your catalog.js you require your controller lke this require('../controllers/horseController') that means you have horseController.js file or horseController is a directory and in which you have an index.js file. After requiring it you save it in horse_controller variable and when you register It as an request handler you specify horse_controller.index
This presume you have exporting in your horseController an object like this
module.export = {
index: function(request, response) {
// Your code goes here
}
}
but if it isn't the case that why your are getting that error
Error: Route.get() requires a callback function but got a [object Undefined]
This code means you have heighter you are exporting nothing in your ../controllers/horseController file or ../controllers/horseController/index.js
If the index.js file under the horseController directory you can pass the horse_controller variable directly as an request handler to the app.get like this
app.get('/', horse_controller);
Passing it directly because in the index.js file you are exporting the Express Router directly
I got this resolved.
I was missing .index function from controller .js file.
added this line
exports.index = function(req, res) {
res.send('NOT IMPLEMENTED: Site Home Page');
};
now .index is no longer looking for an object.
Thanks for the help, appreciate the responses. :)
I've been toying with NodeJS and Express for a few days, and it is pretty cool. But I've run into an issue I cannot get my head around, so I'm hoping someone else out there can help me clear this up.
I know that I can declare a module, and then pass parameters into this module via the require method.
--- App.js ----
var foo = require('./modules/Foo.js');
foo.config();
var bar= {}
require('./modules/Bar.js)(bar, foo)
--- Bar.js ---
module.exports = function(Bar, Foo) {
Bar.act = function(){
Foo.do();
}
}
I think this is a much cleaner design than having to require Foo in every module that would require using it. I also don't have to do initialization in each module that requires it.
But then comes the Router, and I can't really understand how it works. Most examples out there requires the router in each module, something like this:
--- App.js ----
var index = require('./views/index.js');
app.use('/', index);
--- Index.js ---
var express = require('express');
var router = express.Router();
var foo = require('../modules/Foo.js);
foo.config();
router.get('/', function (req, res) {
foo.do();
res.render('index');
})
module.exports = router
But then, I need to require all modules used in index.js manually. What I would really want to do is something like this:
--- App.js ----
var foo = require('../modules/Foo.js);
foo.config();
var index = require('./views/index.js')(foo);
app.use('/', index);
--- Index.js ---
var express = require('express');
var router = express.Router();
module.exports = function(foo){
router.get('/', function (req, res) {
foo.do();
res.render('index');
})
}
But writing it this way, the compiler tells me "Router.use() requires middleware, got a undefined". I can sorta see where this error comes from, (the module.exports does not return an object) but so how do I structure my code so that I can pass parameters to a module that in the end will export a Router middleware? I want to require and initialize Foo in one place, then pass it to all router modules that uses it. Is it possible somehow?
You almost got it, you just need to return the Router.
A fixed index.js could look like this:
var express = require('express');
module.exports = function(foo){
var router = express.Router();
router.get('/', function (req, res) {
foo.do();
res.render('index');
});
return router;
}
Notice the additional ; and the return.
I've also moved the instantiation of the router to the function. In node modules are cached, you can require the same module multiple times and they will all share their global variables. This can lead to unexpected results. In your case you'll overwrite the router.get handler every time and the same instance of Foo would be used for every request.
I am playing with node.js and I don't quite understand why something I set up is working in one instance but if I make a slight change it will not work in another instance.
in my app.js I have
app.use('/musicplayer', require('./routes/music/index'));
in my music\index.js I have
var express = require('express');
var router = express.Router();
router.use('/users', require('./users'));
module.exports = router;
in my users.js I have this - working version
var express = require('express');
var usersRouter = express.Router();
var sqllite3 = require('sqlite3').verbose();
usersRouter.get('/login', function(req, res, next) {
res.render('music/login', { title: 'Express' });
});
module.exports = usersRouter;
But I would like to encapsulate the routes I am defining into another function like this not working this just hangs the page.
Modified version of my users.js not working
var express = require('express');
var usersRouter = express.Router();
var sqllite3 = require('sqlite3').verbose();
var router = function () {
usersRouter.get('/login', function (req, res, next) {
res.render('music/login', {title: 'Express'});
});
return usersRouter;
}
module.exports = router;
In the console I can see it comes in tries the get and nevers gets routed I see this "GET /musicplayer/users/login - - ms - -".
I have even put a console.log right before the return in the anonymous function I created to know it is getting in there and that I am hooking the pathways up right from the parent routes. And I do hit that log action to the screen.
Any help or tips would be appreciated:)
PS in case you are wondering I am trying to separate out apps for different development work I want to play with. So that is why I am doing the sub routing with musicplayer/index.js instead of just putting everything in the app.js for declaring of my main routes.
Router.use() expects an instance of another Router. However your (non-working) module only returns a function.
Use this in your index.js to fix the issue:
router.use('/users', require('./users')());
Dumb/Newb question...
I am learning/working on an API in Node / Express4 and I would like to break my routes out into another module. I have it working with the following code, but it seems awkward to me to keep re-using the require('express') statement... Is there a way to move more of the code from the routes.js file into server.js and still keep my .get and .post statements in the routes module? Thanks in advance!
server.js:
'use strict';
var express = require('express');
var routes = require('./routes');
var app = express();
app.use('/api', routes);
app.listen(3000, function() {
console.log('Listening);
});
routes.js
var express = require('express'); // how do I get rid of this line?
var router = express.Router(); // can I move this to server.js?
var apiRoute = router.route('');
apiRoute.get(function (req, res) {
res.send('api GET request received');
});
module.exports = router;
Your on the right track. Its actually cool to reuse the var express = require('express'); statement each time you need it. Importing, ( requiring ), modules is a cornerstone of modular development and allows you to maintain a separation of concerns with in the files of your project.
As far as modularly adding routes is concerned: The issue is that routes.js is misleading.
In order to modularly separate out your routes you should use several modules named <yourResource>.js. Those modules would contain all of the routing code as well as any other configuration or necessary functions. Then you would attach them in app.js with:
var apiRoute = router.route('/api');
apiRoute.use('/<yourResource', yourResourceRouter);
For example, if you had a resource bikes:
In app.js or even a module api.js:
var apiRoute = router.route('/api')
, bikeRoutes = require('./bikes');
apiRoute.use('/bikes', bikeRoutes);
Then in bike.js:
var express = require('express');
var router = express.Router();
var bikeRoutes = router.route('/');
bikeRoutes.get(function (req, res) {
res.send('api GET request received');
});
module.exports = bikeRoutes;
From there its easy to see that you can build many different resources and continually nest them.
I'm building a web app with Express and Node and am trying to factor my routing so that I don't have hundreds of routes in the same file. This site serves different files within the projects directory, so I made a file in routes/ called projectRoutes.jsto handle the routing for project files:
var express = require('express');
module.exports = function() {
var functions = {}
functions.routeProject = function(req, res) {
res.render('pages/projects/' + req.params.string, function(err, html) {
if (err) {
res.send("Sorry! Page not found!");
} else {
res.send(html);
}
});
};
return functions;
}
Then, in my routes.js, I have this...
var projectRoutes = require("./projectRoutes");
router.get('/projects/:string', function(req, res) {
projectRoutes().routeProject(req, res);
});
Is there a better way to structure this functionality within projectRoutes.js? In other words, how can I configure projectRoutes.js so that I can write the follow line of code in index.js:
router.get('/projects/:string', projectRoutes.routeProject);
The above seems like the normal way to handle something like this, but currently the above line throws an error in Node that says the function is undefined.
Thanks for your help!
You should use the native express router, it was made to solve this exact problem! It essentially lets you create simplified nested routes in a modular way.
For each of your resources, you should separate out your routes into several modules named <yourResource>.js. Those modules would contain all of the routing code as well as any other configuration or necessary functions. Then you would attach them in index.js with:
var apiRoute = router.route('/api')
apiRoute.use('/< yourResource >', yourResourceRouter)
For example, if you had a resource bikes:
In index.js:
var apiRoute = router.route('/api')
, bikeRoutes = require('./bikes')
apiRoute.use('/bikes', bikeRoutes)
Then in bike.js:
var express = require('express')
, router = express.Router()
, bikeRoutes = router.route('/')
bikeRoutes.get(function (req, res) {
res.send('api GET request received')
});
module.exports = bikeRoutes
From there its easy to see that you can build many different resources and continually nest them.
A larger of example of connecting the routes in index.js would be:
var apiRoute = router.route('/api')
, bikeRoutes = require('./bikes')
, carRoutes = require('./cars')
, skateboardRoutes = require('./skateboards')
, rollerskateRoutes = require('./rollerskates')
// routes
apiRoute.use('/bikes', bikeRoutes)
apiRoute.use('/cars', carRoutes)
apiRoute.use('/skateboards', skateboardRoutes)
apiRoute.use('/rollerskates', rollerskateRoutes)
Each router would contain code similar to bikes.js. With this example its easy to see using express's router modularizes and makes your code base more manageable.
Another option is to use the Router object itself, instead of the Route object.
In Index.js:
//Load Routes
BikeRoutes = require('./routes/Bike.js');
CarRoutes = require('./routes/Car.js');
//Routers
var express = require('express');
var ApiRouter = express.Router();
var BikeRouter = express.Router();
var CarRouter = express.Router();
//Express App
var app = express();
//App Routes
ApiRouter.get('/Api', function(req, res){...});
ApiRouter.use('/', BikeRouter);
ApiRouter.use('/', CarRouter);
In Bike.js:
var express = require('express');
var router = express.Router();
router.get('/Bikes', function(req, res){...});
module.exports = router;
Similarly in Car.js