Error: Route.get() , can't seem to get past - node.js

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. :)

Related

Node.js with express routing and sub routing

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

ExpressJS: 'pg'(postgres driver) is not defined on routes/events.js, but it is in routes/index.js file

I have used the express generator plugin and I had all my routes generated on routes/index.js but I'm doing a refactor now and I'm putting all of the routes in it's respective router files. The thing is that the 'pg' module works fine if I put my code on the index.js :
index.js
var express = require('express');
var router = express.Router();
var pg = require('pg');
var connectionString = 'postgres://postgres:postgres#localhost:5432/dataDB';
router.use('/api/events', require('./events'))
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
module.exports = router;
Now if I request a route from the routes/events.js file I get a 'pg'(postgres driver) not defined
var express = require('express');
var router = express.Router();
var pg = require('pg');
var connectionString = 'postgres://postgres:postgres#localhost:5432/dataDB';
//get all events from a user
router.get('/user/id/:id_user', function(req, res) {
.....
});
router.post('/friends/', function(req, res) {
........
});
module.exports = router
And the app.js only includes the router/index.js file ......How can I solve this?. The requests are getting to the router/events.js file correctly, but it's just not recognizing the 'pg' module require......Thank you very much
The problem was that I was including
var pg = require('pg');
in both routes/index.js and in routes/events.js
I removed that line from the index.js and left it only in event.js and now it works perfectly. That require is going in the model layer anyway, but now that I fixed it I would like to know why requiring something on one script and then requiring something on another script fails on express given the fact that I included express and the router in both files and those 2 lines didn't fail but the mentioned line did......

How to efficiently separate routing code

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.

Include a module for all routes at express.js 4

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.

node.js error of callback function in

I am facing an error in my node.js code.
Error: /workspace/Ap/node_modules/express/lib/router/index.js:252
throw new Error(msg);
^
Error: .get() requires callback functions but got a [object Undefined].
Yesterday my code was working fine but today with same code i face above error,
and I don't get where is the problem. My code is:
app.js
var express = require('express');
var routes = require('./routes');
var http = require('http');
var path = require('path');
var app = express();
var mysql = require('mysql');
routes/index.js
module.exports = function(req, res){
res.render('index', { title: 'Express' });
};
Thanks..
Take a look at where you define a GET route, likely at line 252 or thereabouts.
To process a GET in your framework, a callback must be supplied. Currently, your code is supplying [object Undefined], which likely means your object, or exports or whatever is filling that function parameter isn't what you think it is! : )

Resources