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
});
}
});
}
Related
I have created a site using Create React App on the frontend and Node express on the back. I then hosted React on IIS and ran Node as a windows service on the backend.
When running the app I set my callback paths in React (REACT_APP_HOST) to "localhost" and in the node my routes are "/routeName". This being said, the first path called is ${REACT_APP_HOST}/sitemap and the receiving path on the server is router.use('/siteMap', (req, res, next) => siteMapController(req, res, next));.
On the local server, using it as a client, this works perfectly. On a remote client (same domain) I am getting a 404 error.
The next step I tried was changing REACT_APP_HOST to "", making the resulting call to "/sitemap". This has stopped the functioning even on localhost.
Here is my code (app.js, sitemap fetch and server.js). Hoping that someone can give me a clue as to where I am going wrong.
//app.js
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser')
var logger = require('morgan');
var cors = require('cors');
var nodeSSPI = require('express-node-sspi');
let routeList = require('./routes/routeList');
let FileLoader = require('./Controllers/FileLoader');
var app = express();
app.use(bodyParser.json({ limit: '400000' }));
app.use(cors({
origin:['http://localhost', 'http://intranet-test', 'http://intranet'],
credentials: true
}));
app.use(express.static(path.join(__dirname,'../public')));
app.options('*', cors()); // include before other routes
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
//https://www.npmjs.com/package/yarn
app.use(nodeSSPI({
retrieveGroups: false,
offerBasic: false,
authoritative: true,
}));
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')));
routeList(app);
// catch 404 and forward to error handler
app.use(function (req, res, next) {
console.log(req.originalUrl);
console.log(req.method)
next(createError(404));
});
// error handler
app.use(function (err, req, res, next) {
console.log(err);
// 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;
//sitemap fetch
export const fetchInit = () => {
return ({
method: 'GET'
, headers: {
'Content-Type': 'application/json'
}
, credentials: 'include'
})
};
export const Sitemap_Fetch = () => (dispatch) => {
dispatch({
type: ActionTypes.SITEMAP_LOADING
});
var myReq = new Request(`${process.env.REACT_APP_HOST}/siteMap`, fetchInit());//?' + params
return fetch(myReq)
.then((response) => {
// if (response.ok) {
return response;
// }
// else {
// var error = new Error("Error " + response.statusText);
// error.response = response;
// throw error;
// }
},
(error) => {
var err = new Error(error.message);
throw err;
}
)
.then(response => response.json())
.then((data) => {
try {
dispatch({
type: ActionTypes.SITEMAP_LOADED,
payload: data
})
return data;
}
catch (ex) { throw ex }
})
.catch((err) => {
return dispatch({
type: ActionTypes.SITEMAP_FAILED,
payload: err.message
})
});
}
//server.js
#!/usr/bin/env node
/**
* Module dependencies.
*/
var app = require('./app');
var debug = require('debug')('node-backend:server');
var http = require('http');
/**
* Get port from environment and store in Express.
*/
var port = normalizePort('3000');
app.set('port', port);
/**
* Create HTTP server.
*/
var server = http.createServer(app);
/**
* Listen on provided port, on all network interfaces.
*/
server.listen(port, '0.0.0.0');
server.on('error', onError);
server.on('listening', onListening);
server.on('request',test=>{console.log(test)})
/**
* 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();
console.log(addr)
var bind = typeof addr === 'string'
? 'pipe ' + addr
: 'port ' + addr.port;
debug('Listening on ' + bind);
console.log('Listening on ' + bind);
}
Finally I am adding the .env file from my React site
BROWSER=none
SKIP_PREFLIGHT_CHECK=true
REACT_APP_HOST=http://localhost
PORT=80
This works as is. When I change REACT_APP_HOST to nothing it stops functioning.
THanks.
What I have done to solve this is use the serve (https://stackoverflow.com/a/49209041/2242131) command from a simple batch file and run my node backend from another batch. Then in React I created a constant called "hostname" which I set to ${window.location.hostname}:3000. This is now consistently serving my pages the necessary data.
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
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()
I want to execute a set of functions in the order they were written and in the end to release the request to the client.
for example see the mock code bellow:
router.get('/dashboard', function(req, res, next) {
var json = {items : 0}
Q.fcall(
function(){
//first exec
json.items+=1;
}
).then(
function(){
//scond exec
json.items+=1;
}
).then(
function(){
//third exec
json.items+=1;
}
).finally(
function(){
//do this when all the other promises are don
res.json(json);
});
}
the finally function shoud be executed when all is done.
Can it be done with Q?
UPDATE
I think I mislead you, and did not give all the information, because i did not think its relevant, but it is...
I actually bringing data via mongoose, and mongoose is async asd well.
So it goes like this:
Q.fcall(
function() {
Visitor.count(dateRange, function(err, data) {
json.newVisitors = data;
});
}).then(
function() {
Account.count(dateRange, function(err, data) {
json.newAccounts = data;
});
}).finally(
function() {
res.json(json);
})
Mongoose is already promisified. Calling exec() on a query gives you a promise. Here are two ways of doing it:
Classic promises chaining:
Visitor.count(dateRange).exec().then(function (data) {
json.newVisitors = data;
return Account.count(dateRange).exec(); // return promise for chaining
}).then(function (data) {
json.newAccounts = data;
}).then(function () {
res.json(json);
}).catch(function (err) {
// handle errors
});
Or Promise.all:
Promise.all([
Visitor.count(dateRange).exec(),
Account.count(dateRange).exec()
]).then(function(result){
// result is an ordered array of all the promises result
json.newVisitors = result[0];
json.newAccounts = result[1];
}).catch(function (err) {
// handle errors
});
Yes:
var path = require('path'),
express = require('express'),
app = express(),
router = express.Router(),
Q = require('q');
router.get('/dashboard', function(req, res) {
var json = {items:''};
Q.fcall(function() {
json.items += 'A';
})
.then(function() {
json.items += 'B';
})
.then(function() {
json.items += 'C';
})
.finally(function() {
res.json(json);
});
});
app.use('/', router);
var http = require('http');
var port = process.env.PORT || '3000';
app.set('port', port);
var server = http.createServer(app);
server.listen(port);
server.on('listening', function onListening() {
var addr = server.address();
var bind = typeof addr === 'string'
? 'pipe ' + addr
: 'port ' + addr.port;
console.log('Listening on ' + bind);
}
);
Then
curl localhost:3000/dashboard
Returns:
{"items":"ABC"}
P.S. You might also want to investigate async-q et. al.:
async.series([
->
### do some stuff ###
Q 'one'
->
### do some more stuff ... ###
Q 'two'
]).then (results) ->
### results is now equal to ['one', 'two'] ###
doStuff()
.done()
### an example using an object instead of an array ###
async.series({
one: -> Q.delay(200).thenResolve(1)
two: -> Q.delay(100).thenResolve(2)
}).then (results) ->
### results is now equal to: {one: 1, two: 2} ###
doStuff()
.done()
UPDATED (a bit forced, I would just use async):
var path = require('path'),
express = require('express'),
app = express(),
logger = require('morgan'),
router = express.Router(),
Q = require('q'),
async = require('async-q');
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
router.get('/dashboard', function(req, res) {
var json = {};
async.series({
newVisitors: function() {
return Q.Promise(function(resolve,reject) {
console.log(arguments);
Visitor.count(dateRange, function(err, data) {
if(err) return reject(err);
resolve(data);
});
});
},
newAccounts: function() {
return Q.Promise(function(resolve,reject) {
Account.count(dateRange, function(err, data) {
if(err) return reject(err);
resolve(data);
});
});
}
})
.then(function(json) {
res.json(json);
});
});
app.use('/', router);
var http = require('http');
var port = process.env.PORT || '3000';
app.set('port', port);
var server = http.createServer(app);
server.listen(port);
server.on('listening', function onListening() {
var addr = server.address();
var bind = typeof addr === 'string'
? 'pipe ' + addr
: 'port ' + addr.port;
console.log('Listening on ' + bind);
}
);
Now returns:
{"newVisitors": 1,"newAccounts":2}
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();