Error: .get() requires callback functions but got a [object Undefined] - javascript

I am new to node & express and I tried different variations and couldn't figure out why. If I map app.get ('/') to just contentHandler then it works fine. But if I map app.get ('/) to contentHandler.displayWelcomePage then I get the above error. Thanks for looking.
Here is my structure:
app.js
routes/index.js
routes/content.js
app.js
var express = require('express')
, app = express()
, routes = require('./routes')
, http = require('http')
, path = require('path')
, mongoose = require ('mongoose')
, db = mongoose.connection
;
db.on ('error', console.error);
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use (app.router);
routes(app, db);
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
routes/index.js
var contentHandler = require('./content');
//this is what I need to add, see my notes below var aHandler = new contentHandler();
module.exports = exports = function (app, db) {
console.log ('inside routes/index.js');
app.get ('/', contentHandler.displayWelcomePage);
//instead of using contentHandler, use aHandler.displayWelcomePage
};
routes/content.js
function contentHandler (req, res, db) {
console.log ('Inside contentHandler');
res.render('index', {layout: false, title: "Jade is three."});
this.displayWelcomePage = function (req, res) {
return res.render('index', {layout: false, title: "Welcome to Jade"});
};
};
module.exports = contentHandler;

Related

db.getConnection is not a function

I am trying to make a post request to my first app, but every time I go to make the post, it gives me this error: TypeError: db.getConnection is not a function
I have tried all of stack overflows suggestions, but I still can't seem to get it to work after messing around with the code for the last 2 days. I am a beginner so please forgive me, but here is what my code looks like...
my db.js looks like this....
var mysql = require('mysql');
var mainDb = mysql.createPool({
host : process.env.mysql_host,
user : process.env.mysql_user,
password : process.env.mysql_pwd,
database : process.env.mysql_db
});
exports.getConnection = function(callback) {
mainDb.getConnection(function(err, connection) {
if (err) {
console.error('error connecting: ' + err.stack);
return;
}
callback(err, connection);
});
};
and my register.js code looks like this...
var express = require('express');
var router = express.Router();
var db = require(__dirname, 'models/db');
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(bodyParser.json());
router.get('/register', function(req, res, next) {
res.render('register', { title: 'Register for a free account' });
});
router.post('/register', function(req, res) {
var input = JSON.parse(JSON.stringify(req.body));
var today = new Date();
var users = {
"username": req.body.username,
"email":req.body.email,
"password":req.body.password,
"created":today,
"modified":today
};
db.getConnection(function(err, connection) {
connection.query('INSERT INTO users SET ? ', users, function(err, result) {
connection.release();
if (err) { return console.error(err); }
});
});
res.redirect('/index');
});
module.exports = router;
I don't know if my app.js is relevant for this question, but it looks like this...
const express = require('express');
http = require('http');
path = require('path');
session = require('express-session');
app = express();
mysql = require('mysql');
bodyParser = require('body-parser');
db = require(__dirname, 'models/db')
var index = require('./routes/index');
var register = require('./routes/register');
app.use('/', index);
app.use('/', register);
var engine = require('ejs-mate');
app.engine('ejs', engine);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(express.static(path.join(__dirname, 'public')));
var server = http.createServer(app);
var port = 8995;
server.listen(port);
module.exports = app;
When I start app.js I get no errors, only when I make my post request from my form, the error shows up in my browser. Please help!
At db.js you are exporting only a function. But at register.js, you are trying to use db as if it was an object.
To solve your problem, at db.js, just export an object, instead of a function:
function getConnection(callback) {
mainDb.getConnection(function(err, connection) {
if (err) {
console.error('error connecting: ' + err.stack);
return;
}
callback(err, connection);
}
module.exports = { getConnection };
You don't need use getConnection method only exports the pool, according the documentation.
https://github.com/mysqljs/mysql

Node.js browser error Cannot GET/

I'm quite new to Node, I've been following a tutorial to build a simple server that serves dynamic pags with some basic routes but keep getting the Error: Cannot GET/ after running node server.js and calling localhost:3300 on the browser. My routes are defined externally and initialized using a routes.initialise() as follows:
//routes.js
var home = require('../controllers/home'),
image = require('../controllers/image'),
express = require('express');
module.exports.initialize = function(app, router) {
//var router = express.Router();
router.get('/', home.index);
router.get('/images/:image_id', image.index);
router.post('/images', image.create);
router.post('/images/:image_id/like', image.like);
router.post('/images/:image_id/comment', image.comment);
app.use('/', router);
};
I've searched far and wide but no solution forthcoming. I'm really frustrated and will need some help here.
I have a server.js that creates the server:
//server.js
var express = require('express'),
config = require('./server/configure'),
app = express();
app.set('port', process.env.PORT || 3300);
app.set('views', __dirname + '/views');
app = config(app);
var server = app.listen(app.get('port'), function() {
console.log('Server up: http://localhost:' + app.get('port'));
});
and a configure.js that configures the server:
//configure.js
var path = require('path'),
routes = require('./routes'),
exphbs = require('express3-handlebars'),
express = require('express'),
bodyParser = require('body-parser'),
cookieParser = require('cookie-parser'),
morgan = require('morgan'),
methodOverride = require('method-override'),
errorHandler = require('errorhandler');
module.exports = function(app) {
app.engine('handlebars', exphbs.create({
defaultLayout: 'main',
layoutsDir: app.get('views') + '/layouts',
partialsDir: [app.get('views') + '/partials']
}).engine);
app.set('view engine', 'handlebars');
app.use(morgan('dev'));
app.use(bodyParser({
uploadDir:path.join(__dirname, 'public/upload/temp')
}));
app.use(methodOverride());
app.use(cookieParser('some-secret-value-here'));
routes.initialize(app, new express.Router());
app.use('/public/', express.static(path.join(__dirname, '../public')));
if ('development' === app.get('env')) {
app.use(errorHandler());
}
return app;
};
also two files, home.js and image.js which are supposed to provide the default routes from configure.js:
//home.js
module.exports = {
index: function(req, res) {
res.send('The home:index controller');
}
};
//image.js
module.exports = {
index: function(req, res) {
res.send('The image:index controller ' + req.params.image_id);
},
create: function(req, res) {
res.send('The image:create POST controller');
},
like: function(req, res) {
res.send('The image:like POST controller');
},
comment: function(req, res) {
res.send('The image:comment POST controller');
}
};
Anytime I try to GET any of the links on the browser it returns the Cannot GET/ error. Any help will be greatly appreciated.
Thank you so much :)
I actually copied your exact code and it worked as you expect, though frankly it's got a bunch of indirection and at least one deprecated module. Maybe you have a PORT environmental variable set, and so the app isn't actually running on 3300?

Express routing error Cannot Get /api/name

Having some trouble setting up the restful API for my express app.
Here is my app.js:
var express = require('express'),
app = express(),
bodyParser = require('body-parser'),
methodOverride = require('method-override');
routes = require('./routes'),
api = require('./routes/api'),
port = process.env.PORT || 3000;
app.use(express.static(__dirname + '/public'));
app.use(bodyParser.json());
app.use(methodOverride());
app.use(bodyParser.urlencoded({extended: true}));
// Page Routes
app.get('/', routes.index);
app.get('/partials/:filename', routes.partials);
// // API Routes
app.get('/api/name', api.name);
app.listen(port, function() {
console.log('Listening on port ' + port);
});
In /routes/api.js I have the following test function:
exports.name = function (req, res) {
res.json({
name: 'Test'
});
};
Currently I get the following error when i go to http://my_ip/api/name
Cannot GET /api/name
Any ideas?
Thanks
The following code is working for me. I think there is some issue with your routes package. Can you share the code of 'routes' package and file structure ?
app.js
var express = require('express'),
app = express(),
routes = require('./routes');
api = require('./routes/api'),
port = process.env.PORT || 3000;
// Page Routes
app.get('/', routes.index);
// API Routes
app.get('/api/name', api.name);
app.listen(port, function() {
console.log('Listening on port ' + port);
});
/routes/api.js
exports.name = function (req, res) {
res.json({
name: 'Test'
});
};
/routes.js
exports.index = function (req, res) {
res.json({
name: 'Index'
});
};

router.get('/') on expressjs not working

i can't access to my express application's home page by '/' route pattern. it's working on /index e.g. My express version is 4.6.
I tried app.use('/*', router), but my application is not responding or 503 service temporarily unavailable. It's now working by '/index' pattern and other routes is working correctly. only '/' pattern is not working. :)
Here is my code snippet.
var http = require('http');
var express = require('express');
var app = express();
var router = express.Router();
app.use('/', router);
app.set('view engine', 'ejs');
app.set('views', './views');
app.use(express.static('./public'));
var bodyParser = require("body-parser");
app.use(bodyParser());
var fs = require('fs');
var clientSessions = require("client-sessions");
var form = require('express-form');
var field = form.field;
var sha1 = require('sha1');
var mysql = require('mysql');
var connection = mysql.createConnection({
host: process.env.OPENSHIFT_MYSQL_DB_HOST,
port: process.env.OPENSHIFT_MYSQL_DB_PORT,
user: process.env.OPENSHIFT_MYSQL_DB_USERNAME,
password: process.env.OPENSHIFT_MYSQL_DB_PASSWORD,
database: process.env.OPENSHIFT_GEAR_NAME
});
var multer = require('multer');
var done = false;
app.use(clientSessions({
secret: 'xxxxx'
}));
app.use(function(req, res) {
res.status(400);
res.render('pages/404');
});
// Handle 500
app.use(function(error, req, res, next) {
res.status(500);
res.render('pages/500');
});
//---
app.use(multer({
dest: 'public/uploads/',
rename: function(fieldname, filename) {
return filename + Date.now();
},
onFileUploadStart: function(file) {
console.log(file.originalname + ' is starting ...')
},
onFileUploadComplete: function(file) {
console.log(file.fieldname + ' uploaded to ' + file.path)
done = true;
}
}));
//// --------------- start app routes --------------//
// ----- GET -----
router.get('/', function() { // THIS PATTERN IS NOT WORKING
console.log('hello world'); // this line is not working
connection.query(strQuery, function(err, rows) {
// res.render('pages/index');
});
});
Because you didn't handle "/", here is updated code
var router = express.Router();
app.use('/*', router);
router.get('/', function(req, res) {
res.send('welcome home');
}
router.get('/index', function(req, res) {
res.send('welcome index');
}
You are forgetting '*' in second line
app.use('/*', router);
Do you forget to make redirection?
router.get("/", function (req, res) {
res.redirect("/index");
});

Express Middleware being executed out of order

I'm learning about Express middleware. I separated my middleware functions into a simple module. I usually export my modules as an object rather than a function which might be my issue but if so I'd like to know why.. In any case, I'm getting my first middleware function to output before the handler, then the handler, then the first function again. Can someone explain why this is happening?
Here's my main app.js
var express = require('express');
var routes = require('./routes');
var user = require('./routes/user');
var http = require('http');
var path = require('path');
var something = require('./something');
var app = express();
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(something.firstMiddle);
app.use(something.lastMiddle);
app.get('/', something.middleHandler, function(req,res){
res.render('index', { title: 'Yo Mama!' });
});
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
and my module something.js
module.exports = {
middleHandler: function(req,res,next){
console.log('In the handler');
next();
},
firstMiddle: function(req, res, next){
console.log("In first middle!");
next();
},
lastMiddle: function(req,res,next){
console.log('Last middleware');
next();
}
};
It's outputting:
Express server listening on port 3000
In first middle!
In the handler
In first middle!

Categories