Express Server continuously throws 404 error - node.js

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

Related

Can't use passport.authenticate('local')

I posted question here cuz I my passport.authenticate('local') shows nothing, so I cannot use login function. I can activate singup api that I created, but somehow I cannot use my login api that I created as well.
Here is my code below.
var createError = require('http-errors');
var express = require('express');
var ejsMate = require('ejs-mate');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var config = require('./config')
var passport = require('passport')
// var session = require('express-session')
var homeRouter = require('./routes/home');
var usersRouter = require('./routes/users');
const mongoose = require('mongoose')
const url = config.mongoUrl
const connect = mongoose.connect(url)
connect.then((db) => {
console.log('Connected correctly to server')
}, (err) => {console.log(err)})
var app = express();
// view engine setup
//GET, POST, DELETE, PUT
app.engine('ejs', ejsMate)
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(passport.initialize())
//localhost:3000/
app.use('/', homeRouter);
//localhost:3000/users
app.use('/users', usersRouter);
app.use(express.static(path.join(__dirname, 'public')))
// 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;
var express = require('express');
const bodyParser = require('body-parser')
var User = require('../models/users')
var passport = require('passport')
var authenticate = require('../authenticate')
var router = express.Router();
router.use(bodyParser.json())
/* GET users listing. */
router.get('/', (req, res, next) => {
console.log("HAHA")
User.find({})
.then((Users) => {
res.statusCode = 200
res.setHeader('Content-Type', 'application/json')
res.json(Users)
}, (err) => next(err))
.catch((err) => next(err))
});
router.post('/signup', (req, res, next) => {
User.register(new User({username: req.body.username}),
req.body.password, (err, user) => {
if(err) {
res.statusCode = 500;
res.setHeader('Content-Type', 'application/json');
res.json({err: err});
}
else {
if(req.body.firstname)
user.firstname = req.body.firstname
if(req.body.lastname)
user.lastname = req.body.lastname
user.save((err, user) => {
if(err) {
res.statusCode = 500;
res.setHeader('Content-Type', 'application/json');
res.json({err: err});
return;
}
passport.authenticate('local')(req, res, () => {
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.json({success: true, status: 'Registration Successful!'});
})
})
}
})
});
router.post('/login', passport.authenticate('local'), (req, res) => {
var token = authenticate.getToken({_id: req.user._id});
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.json({success: true, token: token, status: 'You are successfully logged in!'});
})
router.get('/logout', (req, res, next) => {
console.log(req.session)
if (req.session) {
req.session.destroy();
res.clearCookie('session-id');
res.redirect('/');
}
else {
var err = new Error('You are not logged in!');
err.status = 403;
next(err);
}
});
module.exports = router;
router.post('/login', passport.authenticate('local') ---> show nothing it keep showing me an error
I need some advice and help.

After refresh "Cannot set headers after they are sent to the client"

I am using express js, mongoose and ejs as templates.
When I refresh my page, in second or third try, I get this error.
Here is my app.js :
{consts..}
var index = require('./routes/index.js');
var users = require('./routes/users.js');
app.set("port", ("2401"));
app.set("views", __dirname + "/views");
app.set("view engine", "ejs");
app.use(express.static(path.join(__dirname, 'public')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use('/', index);
app.use('/users', users);
var port = '2401';
app.set('port', port);
var server = http.createServer(app);
server.listen(port);
server.on('error', onError);
server.on('listening', onListening);
function onError(error) {
if (error.syscall !== 'listen') {
throw error;
}
var bind = typeof port === 'string'
? 'Pipe ' + port
: 'Port ' + port;
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;
}
}
function onListening() {
var addr = server.address();
var bind = typeof addr === 'string'
? 'pipe ' + addr
: 'port ' + addr.port;
console.log('server started on port : ' + app.get('port'));
}
users router :
{consts..}
router.get('/login', function (req, res) {
users.getLogin(req, res);
});
router.post('/login', [
check('email')
.isEmail().withMessage('Please enter a valid email address')
.trim()
.normalizeEmail(),
check('terms', 'Please accept our terms and conditions').equals('yes'),
],
function (req, res) {
users.postLogin(req, res);
});
module.exports = router;
and controller :
usersController.getLogin = function (req, res) {
const connector = mongoose.connect(conStr, { useNewUrlParser: true, useUnifiedTopology: true });
mongoose.connection.on('open', function (ref) {
categories.find(function (err, cats) {
if (err) {
console.log("Error:", err);
}
else {
return res.render("../views/login.ejs", {
_: _,
categories: cats
});
}
});
});
}
index router :
var express = require('express');
var router = express.Router();
var index = require("../controllers/indexController.js");
router.get('/', function (req, res) {
index.list(req, res);
});
module.exports = router;
index controller:
var mongoose = require("mongoose");
var categories = require("../models/categories.js");
var _ = require("underscore");
var indexController = {};
indexController.list = function (req, res) {
const connector = mongoose.connect(conStr, { useNewUrlParser: true, useUnifiedTopology: true });
mongoose.connection.on('open', function (ref) {
categories.find(function (err, cats) {
if (err) {
console.log("Error:", err);
}
else {
console.log("indexe geldi");
return res.render("../views/index.ejs", {
_: _,
categories: cats,
sess: req.session
});
}
})
})
};
module.exports = indexController;
I tried almost everything but still no progress. Can it be about usage of "next()" ?
I also tried the hole router get / post functions with next, mongoose find functions with exec().
The issue is that you're opening a connection to mongo in every route and:
mongoose.connection.on('open' is firing for past requests, requests that are already finished, that's why you're getting Cannot set headers after they are sent to the client.
Move the mongoose.connect & the listener outside of each route.
usersController.getLogin = function (req, res) {
categories.find(function (err, cats) {
if (err) {
console.log("Error:", err);
return res.status(500).send('error');
}
else {
return res.render("../views/login.ejs", {
_: _,
categories: cats
});
}
});
}

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

NodeJS Passport Autehntication Bad Request

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

Resources