node.js error of callback function in - node.js

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

Related

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

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

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

Not able to run "find" query in remote mongodb collection using MongoClient in Node.js application

var express = require("express");
var bodyParser = require('body-parser');
var path = require("path");
var ObjectId = require('mongodb').ObjectID;
var MongoClient = require('mongodb').MongoClient,
format = require('util').format;
var uri = 'mongodb://ac-00072810.devapollogrp.edu:27017/devdb';
MongoClient.connect(uri,function(err,db){
db.collection('TransactionStatus',function(err,collection){
if(err){
throw err;
}
else{
collection.find({}).forEach(function(err,doc){
console.log(doc);
});
}
});
});
Getting Error:
[apol#ac-00067394 nodejs-testapp]$ node Server.js
body-parser deprecated bodyParser: use individual json/urlencoded
middlewares Server.js:15:9
body-parser deprecated undefined extended: provide extended option
node_modules/body-parser/index.js:105:29
Running at Port 3001
undefined
(Note: mongodb version:3.0.2,node version:0.12.7, express version:4.12.4)
From mongo shell I am able to get all the details successfully. But when I am trying to fetch data using mongoClient form the application getting error "undefined". I tried all possibilities. But I don't know what I am doing wrong.
Thanks in advance for your help :)
At a glance it looks like you're getting the [forEach][1] behaviour wrong. The callback passed to forEach accepts three params: currentValue, index and array, respectively, since it's a core Javascript function and not Node-specific (which is why you probably followed the err, doc convention).
Try this in the else block:
collection.find({}).toArray(function(err, docArray){
console.log(docArray);
});

require() in node.js is not working and returns error?

I have looked through stackoverflow and read about require. However I cannot understand why my require function does not run.
app.js code:
var http = require('http');
var express = require("express");
var app = express();
//Twitter Search -------------------
app.get("/tweet, function(req,res){
var twiter = require('twiter.js');
});
app.listen(3000);
twitter.js code:
console.log("twitter.js ran");
Make sure both app.js and twitter.js in same directory
And add ./ before it. Just use following
var twitter = require('./twitter'); // .js extension is not necessary
Also as alexey mentioned. twiter is not same as twitter :)
Take care of your typos. (I think I'm too lazy to read it carefully)
app.js
var http = require('http');
var express = require("express");
var app = express();
//Twitter Search -------------------
app.get("/tweet", function (req, res) {
var twitter = require('./twitter');
twitter.log();
});
app.listen(3000);
twitter.js should be exposed using module.exports
var twitter = {
log: function () {
console.log('twitter is loaded');
}
};
module.exports = twitter;
This should now print "twitter is loaded" in your console, when you visit localhost:3000/tweet

Resources