NodeJS Passport Autehntication Bad Request - node.js

I'm trying to follow a tutorial video on how to use passport with node but for some reason I keep getting a bad request error, I tried some of the example on passport's site, including the custom callbacks as well as some suggestions from forums but no luck. It seems that the program is not even calling passport.use (i tried putting a console message but it doesn't come up at all).
passport-config:
module.exports = function(){
var passport = require('passport');
var passportLocal = require('passport-local');
var userService = require('../services/user-service');
passport.use(new passportLocal.Strategy({usernameField: 'email'}, function(email, password, next){
console.log('========TEST=======');
userService.findUser(email, function(err, user){
if(user){
console.log(user.email + ' found!');
}
if(err){
return next(err);
}
if(!user || user.password != password){
return next(null,false);
}
next(null, user);
});
}));
passport.serializeUser(function(user, next){
next(null, user.email);
});
passport.deserializeUser(function(email, next){
userService.findUser(email, function(err, user){
next(err, user);
});
});
};
User route:
var express = require('express');
var router = express.Router();
var userService = require('../services/user-service');
var passport = require('passport');
/* GET users listing. */
router.get('/', function(req, res, next) {
res.render('users', {
title: 'Users',
description: 'This is the users page'
});
});
router.get('/login', function(req, res, next) {
res.render('users/login', {
title: 'Login',
description: 'Please login'
});
});
router.post('/login', passport.authenticate('local'), function(req, res, next){
res.redirect('/items');
});
module.exports = router;
user-service:
var User = require('../models/user').User;
exports.addUser = function(user, next){
var newUser = new User({
firstName: user.firstName,
lastName: user.lastName,
email: user.email.toLowerCase(),
password: user.password
});
newUser.save(function(err){
if(err){
return next(err);
}
next(null);
});
};
exports.findUser = function(email, next){
User.findOne({email: email.toLowerCase()}, function(err, user){
next(err, user);
});
};
www
#!/usr/bin/env node
/**
* Module dependencies.
*/
var app = require('../app');
var debug = require('debug')('main');
var http = require('http');
/**
* Get port from environment and store in Express.
*/
var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);
/**
* Create HTTP server.
*/
var server = http.createServer(app);
/**
* Listen on provided port, on all network interfaces.
*/
server.listen(port);
server.on('error', onError);
server.on('listening', onListening);
/**
* Normalize a port into a number, string, or false.
*/
function normalizePort(val) {
var port = parseInt(val, 10);
if (isNaN(port)) {
// named pipe
return val;
}
if (port >= 0) {
// port number
return port;
}
return false;
}
/**
* Event listener for HTTP server "error" event.
*/
function onError(error) {
if (error.syscall !== 'listen') {
throw error;
}
var bind = typeof port === 'string'
? 'Pipe ' + port
: 'Port ' + port;
// handle specific listen errors with friendly messages
switch (error.code) {
case 'EACCES':
console.error(bind + ' requires elevated privileges');
process.exit(1);
break;
case 'EADDRINUSE':
console.error(bind + ' is already in use');
process.exit(1);
break;
default:
throw error;
}
}
/**
* Event listener for HTTP server "listening" event.
*/
function onListening() {
var addr = server.address();
var bind = typeof addr === 'string'
? 'pipe ' + addr
: 'port ' + addr.port;
debug('Listening on ' + bind);
}
app.js
var express = require('express');
var path = require('path');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var passport = require('passport');
var expressSession = require('express-session');
var config = require('./config.js');
var routes = require('./routes/index');
var users = require('./routes/users');
var items = require('./routes/items');
var passportConfig = require('./auth/passport-config');
passportConfig();
mongoose.connect(config.mongoUri);
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(expressSession(
{
secret: 'I will achieve my GOALS!',
saveUninitialized: false,
resave: false
}
));
app.use(passport.initialize());
app.use(passport.session());
app.use('/', routes);
app.use('/users', users);
app.use('/items/', items);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;

Try changing your passport variable in your app.js file to use your config instead of the passport module.
var passport = require('./auth/passport-config');
Remove the following from app.js
var passportConfig = require('./auth/passport-config');
passportConfig();

Related

Express Server continuously throws 404 error

I keep getting these errors.
Here's some of my code.
bin/www
#!/usr/bin/env node
/**
* Module dependencies.
*/
var app = require('../app');
var debug = require('debug')('server:server');
var http = require('http');
/**
* Get port from environment and store in Express.
*/
var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);
/**
* Create HTTP server.
*/
var server = http.createServer(app);
/**
* Listen on provided port, on all network interfaces.
*/
server.listen(port);
server.on('error', onError);
server.on('listening', onListening);
/**
* Normalize a port into a number, string, or false.
*/
function normalizePort(val) {
var port = parseInt(val, 10);
if (isNaN(port)) {
// named pipe
return val;
}
if (port >= 0) {
// port number
return port;
}
return false;
}
/**
* Event listener for HTTP server "error" event.
*/
function onError(error) {
if (error.syscall !== 'listen') {
throw error;
}
var bind = typeof port === 'string'
? 'Pipe ' + port
: 'Port ' + port;
// handle specific listen errors with friendly messages
switch (error.code) {
case 'EACCES':
console.error(bind + ' requires elevated privileges');
process.exit(1);
break;
case 'EADDRINUSE':
console.error(bind + ' is already in use');
process.exit(1);
break;
default:
throw error;
}
}
/**
* Event listener for HTTP server "listening" event.
*/
function onListening() {
var addr = server.address();
var bind = typeof addr === 'string'
? 'pipe ' + addr
: 'port ' + addr.port;
debug('Listening on ' + bind);
}
app.js
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var mongoose = require('mongoose');
var eventsRouter = require('./routes/events');
var usersRouter = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested, Content-Type, Accept, Authorization');
res.setHeader(
'Access-Control-Allow-Methods',
'GET, POST, PATCH, DELETE, OPTIONS')
next();
});
app.use('/dashboard', eventsRouter);
app.use('/user', usersRouter);
// catch 404 and forward to error handler
// app.use(function(req, res, next) {
// next(createError(404));
// });
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
mongoose.connect('// this is good just deleted for post')
.then(() => {
console.log("Connected to database!");
})
.catch(() => {
console.log("Connection failed.")
});
module.exports = app;
users.js
const express = require('express');
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
const router = express.Router();
const User = require('../models/user');
router.post('/signup', (req, res, next) => {
bcrypt.hash(req.body.password, 10)
.then(hash => {
const user = new User({
firstName: req.body.firstName,
lastName: req.body.lastName,
userName: req.body.userName,
email: req.body.email,
password: hash
});
user.save()
.then(result => {
res.status(201).json({
msg: "User Created",
rslt: result
});
})
.catch(err => {
res.status(500).json({
err: err
});
});
});
});
router.post("/login", (req, res, next) => {
let fetchedUser;
User.findOne({ email: req.body.email })
.then(user => {
if (!user) {
return res.status(401).json({
msg: "Auth Failed."
});
}
fetchedUser = user;
return bcrypt.compare(req.body.password, user.password)
})
.then(result => {
if (!result) {
return res.status(401).json({
msg: "Auth Failed."
});
}
const token = jwt.sign(
{ email: fetchedUser.email, userId: fetchedUser._id },
// ,
{ expiresIn: '1h' }
);
res.status(200).json({
token: token
});
})
.catch(err => {
return res.status(401).json({
msg: err
});
});
});
router.post("/profile", (req, res, next) => {
})
module.exports = router;
events.js
var express = require('express');
var router = express.Router();
const Event = require('../models/event');
const checkAuth = require('../middleware/check-auth');
router.post("/createEvent", checkAuth, (req, res, next) => {
const event = new Event({
title: req.body.title,
description: req.body.description,
date: req.body.date,
time: req.body.time,
location: req.body.location,
invite: req.body.invite,
private: req.body.private
});
event.save()
.then(result => {
res.status(201).json({
msg: "Event Created",
rslt: result
});
})
.catch(err => {
res.status(500).json({
err: err
});
});
});
module.exports = router;
Any suggestions on what I am doing wrong. It's a project that I started a couple of months ago and of course, didn't finish it. I just recently came back to it and can't seem to figure out why my server won't work. Seems to connect fine with the database.
As I can see, your typing '/' url, but in your code there is no '/' route.
Can you add the 'home' route as following, and check again please ?
app.use('/dashboard', eventsRouter);
app.use('/user', usersRouter);
// catch 404 and forward to error handler
// app.use(function(req, res, next) {
// next(createError(404));
// });
app.get('/', (req, res) => {
res.send('home');
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
#RickyMed have you defined any middleware for / route. Generally 404 Not Found came when url is not present. If not create one or try http://localhost:3000/user.
Check if this is working

Nodejs Server is Running and localhost didn’t send any data on express project

I working on Building a shopping cart Using Node.js Express and mongodb, using this tutorial, and so far there is no problem, but now when i run the server, it shows '
Server running on port 3000
' But the problem is when I connect to localhost:3000 it shows,
This page isn’t working localhost didn’t send any data.
ERR_EMPTY_RESPONSE
I check some error logs but didn't work. DB connection is also working, and DB has fetching data
There is no error shown in the terminal, How to solve this
my bin/www code
#!/usr/bin/env node
/**
* Module dependencies.
*/
var app = require('../app');
var debug = require('debug')('shopping-cart:server');
var http = require('http');
/**
* Get port from environment and store in Express.
*/
var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);
/**
* Create HTTP server.
*/
var server = http.createServer(app);
/**
* Listen on provided port, on all network interfaces.
*/
server.listen(port);
server.on('error', onError);
server.on('listening', onListening);
/**
* Normalize a port into a number, string, or false.
*/
function normalizePort(val) {
var port = parseInt(val, 10);
if (isNaN(port)) {
// named pipe
return val;
}
if (port >= 0) {
// port number
return port;
}
return false;
}
/**
* Event listener for HTTP server "error" event.
*/
function onError(error) {
if (error.syscall !== 'listen') {
throw error;
}
var bind = typeof port === 'string'
? 'Pipe ' + port
: 'Port ' + port;
// handle specific listen errors with friendly messages
switch (error.code) {
case 'EACCES':
console.error(bind + ' requires elevated privileges');
process.exit(1);
break;
case 'EADDRINUSE':
console.error(bind + ' is already in use');
process.exit(1);
break;
default:
throw error;
}
}
/**
* Event listener for HTTP server "listening" event.
*/
function onListening() {
var addr = server.address();
var bind = typeof addr === 'string'
? 'pipe ' + addr
: 'port ' + addr.port;
debug('Listening on ' + bind);
}
my app.js code
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var indexRouter = require('./routes/index');
var expressHbs = require('express-handlebars');
var mongoose = require('mongoose');
var session = require('express-session');
var passport = require('passport');
var flash = require('connect-flash');
var app = express();
mongoose.connect('mongodb://localhost:27017/shopping',{ useNewUrlParser: true });
require('./config/passport');
// view engine setup
app.engine('.hbs',expressHbs({defaultLayout: 'layout', extname: '.hbs'}));
app.set('view engine', '.hbs');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(session({secret: 'mysupersecert', resave: false, saveUninitialized: false}));
app.use(flash);
app.use(passport.initialize());
app.use(passport.session());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
my index.js code
var express = require('express');
var router = express.Router();
var csrf = require('csurf');
var passport = require('passport');
var Products = require('../models/product');
var csurfProtection = csrf();
router.use(csurfProtection);
/* GET home page. */
router.get('/', function(req, res, next) {
Products.find(function (err, docs) {
var productChunks = [];
var chunkSize = 4;
for (var i = 0; i < docs.length; i += chunkSize) {
productChunks.push(docs.slice(i, i + chunkSize))
}
res.render('shop/index', { title: 'Shopping Cart', products: productChunks });
});
});
router.get('/user/signup', function (req, res, next) {
res.render('user/signup',{csrfToken: req.csrfToken()})
});
router.post('/user/signup',passport.authenticate('local.signup', {
successRedirect: 'user/profile',
failureRedirect: 'user/signup',
failureFlash: true
}));
router.get('user/profile', function (req, res, next) {
res.render('user/profile')
});
module.exports = router;
and my passport.js code
var passport = require('passport');
var User = require('../models/user');
var LocalStrategy = require('passport-local').Strategy;
passport.serializeUser(function (user, done) {
done(null, user.id);
});
passport.deserializeUser(function (id, done) {
User.findById(id,function (error, user) {
done(err, user)
})
});
passport.use('local.signup', new LocalStrategy({
userNameFeild: 'email',
passwordFeild: 'password',
passReqToCallback: true
}, function (req, email, password, done) {
User.findOne({'email': email}, function (err, user) {
if (err) {
return done(err);
}
if (user) {
return done(null, false, {message: 'Email Already in use'})
}
var newUser = User;
newUser.email = email;
newUser.password = newUser.encryptPassword(password);
newUser.save(function (err, result) {
if (err) {
return done(err);
}
return done(null, newUser);
})
})
}));
and my product.js code
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var schema = new Schema({
imagePath: {type: String, required: true},
title: {type: String, required: true},
description: {type: String, required: true},
price: {type: Number, required: true}
});
module.exports = mongoose.model('product', schema);
Please help me out
If your call to Products.find in index.js returns nothing the code doesn’t complete the http transaction.
Suggest you test for that case and complete the transaction with res.end()

NodeJS app using CSRF for web and JWT for API does async.parallel out of order

When a logged-in user gets to a page through the browser using EJS I'm able to get the function to do what it's supposed to but when I use the API with Ionic using a logged in user with JWT, the async.parallel function doesn't "wait" to do things in order.
Here is my function:
console.log('1');
async.parallel([
function(callback){
buildAlertButtonsArray.getRealTestAlerts(req,function(arrayAlerts) {
console.log('2');
callback(null, arrayAlerts);
});
},
function(callback) {
if(req.decoded) //API
callback('API');
else //EJS
functions.aclSideMenu(req, res, function (acl) {callback(null, acl);}); //aclPermissions sideMenu
}
],function(err, results){
console.log('3');
})
when I login through the browsed on my console.log() is 1, 2, 3 but when I login through the API using JWT I get 1, 3, 2.
Here is my 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 app = express();
var bluebird = require('bluebird');
//me
var mongoose = require('mongoose');
var db = mongoose.connection;
var cors = require('cors');
var session = require('client-sessions');
var flash = require('express-flash');
//.js file
var routesApi = require('./routes/api');
var routesEjs = require('./routes/ejs');
var routes = require('./routes/index');
//var login = require('./routes/authentication/login');
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(cookieParser());
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(express.static(path.join(__dirname, 'public')));
app.use(bodyParser.urlencoded({ extended: true })); //was FALSE by default. was TRUE for auth Template
// middleware
app.use(session({
cookieName: 'session',
secret: 'mysecret',
duration: 30 * 60 * 1000,
activeDuration: 30 * 60 * 1000,
httpOnly: true, //doesn't let javascript access cookies ever
secure: true, // only use cookies over https
ephemeral: true // delete this cookie when the browser is closed (nice when people use public computers)
}));
app.use(flash());
app.use(function(req, res, next){
res.locals.success_messages = req.flash('success_messages');
res.locals.error_messages = req.flash('error_messages');
next();
});
// use cors
app.use(cors());
app.use('/public', express.static(path.join(__dirname, 'public')));
app.use('/api', routesApi);
app.use('/', routes);
app.use('/', routesEjs);
//bluebird
mongoose.Promise = require('bluebird');
//connecting to database
mongoose.connect('mongodb://myip:2999/SMECS_database', { useMongoClient: true });
//if we connect successfully or if a connection error occurs
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function (callback) {
// yay!
});
// error handlers
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
Here is my Login function for both EJS using CSRF and API using JWT:
module.exports.postLogin = function(req, res, next) {
if (req.body.pushToken) { // run SMECS API
models.Users.findOne({
email: req.body.email.toLowerCase()
}, function (err, user) {
if (err) throw err;
if (!user) {
res.json({success: false, message: 'Authentication failed. User not found.'});
} else if (user) {
//check if password matches
if (!bcrypt.compareSync(req.body.pin, user.pin)) {
res.json({success: false, message: 'Authentication failed. Wrong password.'});
} else {
// if user is found and password is right
// create a token
var token = jwt.sign({user: user}, config.secret, {
//expiresIn: 1440 // expires in 24 hours
});
user.save(function (err) {
if (err) {
res.json({
success: false,
message: 'contact your system administrator. pushToken not saved'
});
} else {
// return the information including token as JSON
res.json({
success: true,
message: 'Welcome aboard!',
token: token,
userRoleID: user.userRoleID,
userRoleName: user.userRoleName,
userPrivilegeID: user.userPrivilegeID,
userPrivilegeName: user.userPrivilegeName,
firstName: user.firstName,
lastName: user.lastName,
email: user.email
});
}
});
}
}
});
}
else { //run SMECS EJS
models.Users.findOne({email: req.body.email.toLowerCase()}, function (err, user) {
if (!user || user.softDeleted !== null) {
//Parent Self Registration Login
models.ParentSelfRegistration.findOne({email: req.body.email.toLowerCase()}, function (err, parentSelfRegistration) {
if (!parentSelfRegistration) {
res.render('login', {error: "ERROR: Incorrect email or pin.", csrfToken: req.csrfToken()});
} else {
if (req.body.pin == parentSelfRegistration.pin) {
req.session.user = parentSelfRegistration;
res.redirect('/parentsSelfRegistration/registerParentStep1');
} else {
res.render('login', {error: "ERROR: Incorrect email or pin.", csrfToken: req.csrfToken()});
}
}
});
//END OF checks for users in UtilityUsers database
} else {
if (bcrypt.compareSync(req.body.pin, user.pin)) { // if user is found and password is right
req.session.user = user;
res.redirect('/dashboard');
//}
} else {
//res.status(400).send('Current password does not match');
res.render('login', {error: "ERROR: Incorrect email or pin.", csrfToken: req.csrfToken()});
//res.render('login', { error: "ERROR: Incorrect email or pin."});
}
}
});
}
};
Here is my ejs.js file:
//Dependencies
var express = require('express');
var routerEjs = express.Router();
var login = require('./authentication/login');
var auth = require('./authentication/auth');
var chooseAlert = require('./alerts/sendingReceiving/1.chooseAlert');
var login = require('./authentication/login');
var csrf = require('csurf');
routerEjs.use(csrf());
/* GET login page. */
routerEjs.get('/login', login.getLogin, function(req, res) {});
routerEjs.post('/login', login.postLogin, function(req, res) {});
routerEjs.get('/logout', login.getLogout, function(req, res) {});
module.exports = routerEjs;
and my api.js file:
//Dependencies
var express = require('express');
var routerApi = express.Router();
var login = require('./authentication/login');
var auth = require('./authentication/auth');
var chooseAlert = require('./alerts/sendingReceiving/1.chooseAlert');
routerApi.post('/login', login.postLogin, function(req, res) {});
routerApi.get('/chooseGroup', auth.auth, chooseAlert.showGroups, function(req, res) {});
routerApi.get('/alerts/sending/chooseAlert', auth.auth, chooseAlert.showAlerts, function(req, res) {});
/* Update pushToken ------------------------------------*/
routerApi.post('/updatePushToken', auth.auth, auth.pin, function(req, res) {});
module.exports = routerApi;
I figured out my problem. I was missing a NULL on my callback...
console.log('1');
async.parallel([
function(callback){
buildAlertButtonsArray.getRealTestAlerts(req,function(arrayAlerts) {
console.log('2');
callback(null, arrayAlerts);
});
},
function(callback) {
if(req.decoded) //API
callback(NULL, 'API');
else //EJS
functions.aclSideMenu(req, res, function (acl) {callback(null, acl);}); //aclPermissions sideMenu
}
],function(err, results){
console.log('3');
})

TypeError: "Object is not a function" when using a constructor

I am making a user registration form witch insert a record to the mongodb. I am using there fore:
MongoDB version v2.6.11
NodeJS version v0.10.25
Express version 4.13.1
All works fine except when a use a constructor var newUser = new User({...}); it returns the error Object is not a function
The rest works fine. I get the logging before it returns the error but i don't know how to fix this.
users.js
var express = require('express');
var router = express.Router();
var User = require('../models/user');
/* GET users listing. */
router.get('/', function(req, res, next) {
res.send('respond with a resource');
});
router.get('/Registreren', function(req, res, next) {
res.render('Registration', { title: 'Registreren' });
});
router.get('/Aanmelden', function(req, res, next) {
res.render('Aanmelden', { title: 'Aanmelden' });
});
router.post('/Registreren', function(req, res, next){
// Get form value
console.log('Bericht in behandeling ...')
var username = req.body.username;
var email = req.body.email;
var password = req.body.password;
var password_confirm = req.body.password_confirm;
console.log('username: ' + username);
console.log('email: ' + email);
console.log('password: ' + password);
console.log('password_confirm: ' + password_confirm);
console.log('FIRST TEST: ' + JSON.stringify(req.file));
console.log('SECOND TEST: ' + req.file.profileimage);
console.log('THIRD TEST: ' + req.file.originalname);
// Check for image field
if (req.file || req.file.profileImage){
console.log('Uploading file....');
//File Info
var profileImageOrginalName = req.file.originalname;
var profileImageName = req.file.name;
var profileImageMimetype = req.file.mimetype;
var profileImagePath = req.file.path;
var profileImageExt = req.file.extension;
var profileImageSize = req.file.size;
} else{
console.log('profileImageFile not found....');
// Set default image
var profileImageName = 'noimage.png';
}
// Form validation
req.checkBody('username','Gebruikersnaam is verplicht').notEmpty();
req.checkBody('email','email is verplicht').notEmpty();
req.checkBody('email','email is niet geldig').isEmail();
req.checkBody('username','Gebruikersnaam is verplicht').notEmpty();
req.checkBody('password','Wachtwoord is verplicht').notEmpty();
req.checkBody('password_confirm','Wachtwoorden zijn niet `gelijk').equals(req.body.password);`
// Error handling
var errors = req.validationErrors();
console.log(errors);
if(errors){
console.log('Error handling....');
res.render('Registration',{
errors: errors,
email: email,
username: username,
password: password,
password_confirm: password_confirm
});
} else {
console.log('Make new User ....');
console.log('email: ' + email);
console.log('username: ' + username);
console.log('password: ' + password);
console.log('profileImageName: ' + profileImageOrginalName);
var newUser = new User({
email: email,
username: username,
password: password,
profileimage: profileImageOrginalName
});
console.log('---------------- START TEST----------------------------');
console.log('FIRST TEST: ' + JSON.stringify(newUser));
console.log('SECOND TEST: ' + newUser);
// Create User
User.createUser(newUser, function(err,user){
if(err) throw err;
});
// Succes message
req.flash('succes','Je bent succesvol aangemedld');
res.location('/');
res.redirect('/');
}
});
module.exports = router;
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 session = require('express-session');
var methodOverride = require('method-override');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var multer = require('multer');
var flash = require('connect-flash');
var expressValidator = require('express-validator');
var mongo = require('mongodb');
var mongoose = require('mongoose');
var db = mongoose.connection;
var routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// Handle file Uploads
app.use(multer({dest:'./uploads/'}).single('profileimage'));
// 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: false }));
//Handle Express Sessions
app.use(session({
secret: 'secret',
saveUninitialized: true,
resave: true
}));
//Passport
app.use(passport.initialize());
app.use(passport.session());
//Vallidator
app.use(expressValidator({
errorFormatter: function(param, msg, value) {
var namespace = param.split('.')
, root = namespace.shift()
, formParam = root;
while(namespace.length) {
formParam += '[' + namespace.shift() + ']';
}
return {
param : formParam,
msg : msg,
value : value
};
}
}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
// Flash
app.use(flash());
app.use('/', routes);
app.use('/users', users);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
user.js
console.log('Mongoose Start....');
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/Users');
var db = mongoose.connection;
db.once('open', function (callback) {
//user Schema
var UserSchema = mongoose.Schema({
username: {
type: String,
index: true
},
password: {
type: String,
},
email: {
type: String,
},
profileimage: {
type: String,
}
});
console.log('Create record!');
var User = module.exports = mongoose.model('User',UserSchema);
module.exports.createUser = function(newUser, callback){
newUser.save(callback);
console.log('USER: ' + newUser)
};
});
What i have tried an read
I have read the following post:
Node.js: object is not a function
node.js express.js object is not a function call_non_function
TypeError: object is not a function Node.js
I have tried to build more logging as you can see in the scripts so i can pin point where the problem come from. But i don know how to fix this. I hope you can help me.

404 when attempting rooting with param on Express

i get 404 error when rooting with param , whereas all other rootings defined on my rootes/users.js file work perfectly , for example i get the desire result when i call :
localhost:3000/users/users .
but get 404 when i call localhost:3000/users/users/12315454 which should correspond to the rooter /users:user_id in my users.js (you can find it below)
var express = require('express');
var router = express.Router();
var User = require('../models/user');
router.route('/users:user_id')
.get(function(req, res) {
console.log("attempting user");
User.findById(req.params.user_id, function(err, place) {
if (err)
res.send(err);
res.json(place);
});
})
.put(function(req, res) {
console.log("attempting to update user");
User.findById(req.params.user_id, function(err, place) {
if (err)
res.send(err);
user.username = req.body.name;
user.visitedPlaces = req.body.visitedPlaces;
user.likedItems = req.body.likedItems;
//user.local.email= req.body.email;
user.save(function(err) {
if (err)
res.send(err);
res.json({ message: 'user updated!' });
});
});
})
.delete(function(req, res) {
User.remove({
_id: req.params.user_id
}, function(err, bear) {
if (err)
res.send(err);
res.json({ message: 'Successfully deleted' });
});
});
router.route('/users')
// get all the users (accessed at GET http://localhost:8080/api/users)
.get(function(req, res) {
User.find(function(err, places) {
if (err)
res.send(err);
res.json(places);
});
});
router.route('/adduser')
.post(function(req, res) {
var user = new User();
user.password = user.generateHash (req.body.password); // set the users name (comes from the request)
user.username = req.body.username;
console.log(req.body)
console.log("user name :"+req.body.username);
user.save(function(err) {
if (err)
res.send(err);
res.json({ message: 'user created!' });
});
});
module.exports = router;
my app.js config
var express = require('express');
var path = require('path');
var favicon = require('static-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');
var passport = require('passport');
var FacebookStrategy = require('passport-facebook').Strategy;
var mongo = require('mongoskin');
var mongoose = require('mongoose');
var configDB = require('./config/database.js');
var port = process.env.PORT || 3030;
var router = express.Router();
// configuration ===============================================================
mongoose.connect(configDB.url); // connect to our database
//Facebook app credentials
var FACEBOOK_APP_ID = '******09';
var FACEBOOK_APP_SECRET = '9a*******3';
//app secret for dev = 9adfcaa6d7989d8adc12852badcf69f3
// app ifd for dev = 492502667544609
var app = express();
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'app')));
//var routes = require('./routes/index');
require('./config/passport')(passport); // pass passport for configuration
var users = require('./routes/users');
var places = require('./routes/places');
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// set up our express application
app.use(logger('dev')); // log every request to the console
app.use(cookieParser()); // read cookies (needed for auth)
app.use(bodyParser()); // get information from html forms
// required for passport
app.use(session({ secret: 'ilovescotchscotchyscotchscotch' })); // session secret
app.use(passport.initialize());
app.use(passport.session());
app.use(favicon());
//app.use(flash()); // use connect-flash for flash messages stored in session
// Make our db accessible to our router WARNING THIS MUST BE PUT before the rooting stuff above
app.use('/api', router);
app.use('/places', places);
app.use('/users', users);
// routes ======================================================================
require('./routes/routes.js')(app, passport); // load our routes and pass in our app and fully configured passport
app.get('/', function(req, res, next) {
res.sendfile('./app/index.html');
});
/// catch 404 and forwarding to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
/// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
// test authentication
function ensureAuthenticated(req, res, next) {
if (req.isAuthenticated()) { console.log("is authenticated");
return next(); }
console.log("not authenticated");
res.redirect('/')
}
// launch ======================================================================
console.log('The magic happens on port ' + port)
module.exports = app;
Add a slash in your route, between the users and :user_id:
router.route('/users/:user_id')
^---------here

Resources