The only file/folder ive changed is the main app.js after i installed express generator and npm install. Im a newb, maybe its its a typo in the app.js file. Heres the file and console output. Thanks so much. when i go to localhost:3000 on chrome it says cannot GET/ and it failed to load resource in console 404 and on the comm line it says GET / 404 11.960 ms - 13 everytime i reload the page
^Cryan#\Ryan:~/Desktop/node/frameworks/expressapi$ npm start
> expressapi#0.0.0 start /home/ryan/Desktop/node/frameworks/expressapi
> node ./bin/www
curl -X get http://localhost:3000/products
curl -X DELETE http://localhost:3000/products/2
and the app.js file
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 routes = require('./routes');
var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// 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 }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
var products = [
{
id: 0,
name: 'watch',
description: 'tell time with this amazing watch',
price: 30.00
},
{
id: 1,
name: 'sandals',
description: 'walk in comfort with these sansdals',
price: 10.00
},
{
id: 2,
name: 'watch',
description: 'protect your eyes!',
price: 25.00
}
];
app.get('./routes');
app.get('/products', function(req, res) {
res.json(products);
});
app.get('/products/:id', function(req, res) {
if (req.params.id > (products.length - 1) || req.params.id < 0) {
res.statusCode = 404;
res.end('NotFound');
}
res.json(products[req.params.id]);
});
app.post('/products', function(req, res) {
if (typeof req.body.name === 'undefined') {
res.statusCode = 400;
res.end('a product name is required');
}
products.push(req.body);
res.send(req.body);
});
app.put('/products/:id', function(req, res) {
if (req.params.id > (products.length - 1) || req.params.id < 0) {
res.statusCode = 404;
res.end('not found');
}
products[req.params.id] = req.body;
res.send(req.body);
});
app.delete('/products/:id', function(req, res) {
if (req.params.id > (products.length - 1) || req.params.id < 0) {
res.statusCode = 400;
res.end('not found for that id');
}
products.splice(req.params.id, 1);
res.json(products);
});
module.exports = app;
and here iis the www file
#!/usr/bin/env node
/**
* Module dependencies.
*/
var app = require('../app');
var debug = require('debug')('expressapi: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);
}
I run your code and it looks fine. It does not have a route for "/", so you will get a Cannot GET / message in the browser if you enter http://localhost:3000/
http://localhost:3000/products returns your JSON data correctly.
For the curl command you have to use GET in capital letters:
curl -X GET http://localhost:3000/products
[{"id":0,"name":"watch","description":"tell time with this amazing watch","price":30},{"id":1,"name":"sandals","description":"walk in comfort with these sansdals","price":10},{"id":2,"name":"watch","description":"protect your eyes!","price":25}]
If you want to add the default '/' route from express generator, change your app.js file on line with this code:
var routes = require('./routes/index');
And then add the following line later on in the code:
app.use('/', routes);
You will then see the Welcome to Express message when you point your browser to http://localhost:3000
I hope that helps clarify.
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 created a sample ExpressJS App by using Express Application Generator
I want to call localhost:3000/data to get some data. I added these code to app.js:
app.get('/data', function(req, res){
debug("get data");
});
Also I make ajax request in client side js file :
$.ajax({
url: 'http://localhost:3000/data/',
//url: 'http://localhost:3000/data', -> also not work
type:'GET',
dataType: 'json',
success: (data) => {
console.log("get data from client js", data);
}
});
but my app.get method never call. GET /data/ 404 written in console screen. Also when I typed http://localhost:3000/data on browser I got Not Found error. how can I fix this ?
my www file :
#!/usr/bin/env node
/**
* Module dependencies.
*/
var app = require('../app');
var debug = require('debug')('myapp: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);
}
I'm not exactly sure where your problem lies because there isn't enough code displayed to determine that. instead I have written a simple express server for you to use:
const express = require('express');
const bodyParser = require('body-parser');
const CORS = require('cors');
const app = express();
app.use(bodyParser.json());
app.use(CORS());
app.get('/data', (req, res) => {
res.json({message: "working"});
});
app.listen(5000, () => {
console.log('Server listening on port 5000');
});
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 am currently trying to run node es6 with babel on a docker container and am running into some issues getting the app to start listening on port 3000. I can see where the app.js file is being processed as I am seeing the database connection code running. The problem seems to be even though app.js is getting called I am not seeing anything from /bin/www getting called which would result in the server listening on port 3000.
This is the command that is getting called to start the container:
nodemon ./bin/www -L --exec babel-node --inspect=0.0.0.0:56745
app.js:
……
(async () => {
try {
console.log('about to start the database connection... - 1');
mongoose.set('useCreateIndex', true);
mongoose.Promise = global.Promise;
console.log('about to start the database connection... - 2');
setTimeout(async () => {
await mongoose.connect(process.env.DB_HOST, {useNewUrlParser: true});
}, 60000);
//await mongoose.connect(process.env.DB_HOST, {useNewUrlParser: true});
console.log('about to start the database connection... - 3');
let db = mongoose.connection;
console.log('about to start the database connection... - 4');
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
console.log('about to start the database connection... - 5');
} catch (e) {
console.log('We have an error.....');
console.log(e);
}
})()
let app = express();
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(helmet());
app.use(methodOverride());
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/group', groupsRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use((err, req, res, next) => {
if (process.env.NODE_ENV === "development") {
app.use((err, req, res, next) => {
if (err instanceof NotFoundError) {
//res.status(404).send(err.message);
res.statusCode = 404;
return res.json({
errors: [err.stack]
});
} else {
//res.status(500).send('An error occurred while processing your request.');
res.statusCode = 500;
return res.json({
errors: [err.stack]
//errors: ['An error occurred while processing your request.']
});
}
});
}
// production error handler
// no stacktraces leaked to user
console.log('about to begin configurations..... 7');
if (process.env.NODE_ENV !== "development") {
app.use((err, req, res, next) => {
if (err instanceof NotFoundError) {
//res.status(404).send(err.message);
res.statusCode = 404;
return res.json({
errors: [err.stack]
});
} else {
//res.status(500).send('An error occurred while processing your request.');
res.statusCode = 500;
return res.json({
errors: [err.stack]
//errors: ['An error occurred while processing your request.']
});
}
});
}
});
module.exports = app;
/bin/www:
#!/usr/bin/env node
/**
* Module dependencies.
*/
let app = require('../app');
let debug = require('debug’)(‘myapp:server');
let http = require('http');
/**
* Get port from environment and store in Express.
*/
let port = normalizePort(process.env.PORT || '3000');
app.set('port', port);
/**
* Create HTTP server.
*/
let 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.
*/
const normalizePort = (val) => {
debug('port = ' + val);
let 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.
*/
const onError = (error) => {
debug('Houston we have a problem');
if (error.syscall !== 'listen') {
throw error;
}
let 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.
*/
const onListening = () => {
debug('Listening');
let addr = server.address();
let bind = typeof addr === 'string'
? 'pipe ' + addr
: 'port ' + addr.port;
debug('Listening on ' + bind);
}
.babelrc:
{
"presets": ["env"],
"plugins": ["transform-object-rest-spread", "transform-async-to-generator"]
}
Update:
The issue seems to be with node and the arrow operator. When I changed to the function keyword, it started working. I added the following to my .bablerc file:
{
"presets": ["env"],
"plugins": ["transform-object-rest-spread", "transform-async-to-generator", "transform-es2015-arrow-functions"]
}
but it is still an issue. How can I use the arrow operator with nodejs?
If you aren't able to progress past the normalizePort call, are you sure it exists at that time?
You need to move the definition of the function above the place you use it.
(If you are used to old, pre-ES6 "function hoisting" using vars and functions, you should note that that does not work with const and let statements.)
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();