can no longer load express app webpages - node.js

So i've been working on getting a user authentication system going and then I encountered a problem where my webpages would no longer load. npm start works fine and the server appears to be running. going to localhost just shows that the bar keeps loading and never eventually loads (before the webpages loaded instantly). I have no idea what I changed but tried to revert as much of the code to the original but still no dice. let me know if any other files are needed. thanks in advance
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 mongoose = require('mongoose');
var passport = require('passport');
var session = require('express-session');
var LocalStrategy = require('passport-local').Strategy;
var flash = require('connect-flash');
// var users = require('./routes/users');
var routes = require('./routes/index');
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(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser('ground glass'));
app.use(express.static(path.join(__dirname, 'public')));
app.use(passport.initialize());
app.use(flash);
app.use(session({
secret: 'keyboard cat',
resave: false,
saveUninitialized: true
}));
app.use('/', routes);
//app.use('/users', users);
// passport config
// var Account = require('./models/accounts');
//passport.use(new LocalStrategy(Account.authenticate()));
//passport.serializeUser(Account.serializeUser());
//passport.deserializeUser(Account.deserializeUser());
// mongoose
//mongoose.connect('mongodb://localhost/test');
// Using the flash middleware provided by connect-flash to store messages in session
// and displaying in templates
//var flash = require('connect-flash');
//app.use(flash());
//require('./routes/index')(app);
/*
passport.use(new LocalStrategy(
function(username, password, done) {
User.findOne({ username: username }, function(err, user) {
if (err) { return done(err); }
if (!user) {
return done(null, false, { message: 'Incorrect username.' });
}
if (!user.validPassword(password)) {
return done(null, false, { message: 'Incorrect password.' });
}
return done(null, user);
});
}
));*/
// 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;
index.js
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res) {
res.render('index', { title: 'test' });
});
module.exports = router;

Related

VueJs Web Applications is Failed Authenticate User

I creating e commerce project . I want to user must have account in order to proceed the checkout process . I am able to create new user with the database but the problem is even the user is login and click buy button ,Still it is showing message user must be login. I want once the user is login then user will be able to buy products..
Here is my app.js code .
'use strict';
var debug = require('debug');
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 { User } = require('./db');
var session = require('express-session');
var passport = require('./passport');
var routes = require('./routes/api/index');
//var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
// uncomment after placing your favicon in /public
//app.use(favicon(__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')));
app.use('/api', require('./routes/api').route);
//app.use('/', routes);
//app.use('/users', users);
app.use(session({
secret: 'some very very secret thing',
resave: false,
saveUninitialized: true
}));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(passport.initialize());
app.use(passport.session());
app.post('/signup', (req, res) => {
User.create({
username: req.body.username,
password: req.body.password
}).then((user) => {
if (user) {
res.redirect('/signin.html');
}
}).catch((err) => res.send("ERROR CREATING USER"));
});
app.post('/signin', passport.authenticate('local', {
failureRedirect: '/signin.html',
// successRedirect: 'profile'
successRedirect: '/index.html'
}));
// 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: {}
});
});
app.set('port', process.env.PORT || 3000);
var server = app.listen(app.get('port'), function () {
debug('Express server listening on port ' + server.address().port);
});
Here is the user.js code .
var route = require('express').Router();
var { User } = require('../../db');
var session = require('express-session');
var passport = require('../../passport');
route.use(session({
secret: 'some very very secret thing',
resave: false,
saveUninitialized: true
}));
route.use(passport.initialize());
route.use(passport.session());
route.post('/signup', (req, res) => {
User.create({
username: req.body.username,
password: req.body.password
}).then((user) => {
if (user) {
res.redirect('/signin.html');
}
}).catch((err) => res.send("ERROR CREATING USER"));
});
route.post('/signin', passport.authenticate('local', {
failureRedirect: '/signin.html',
// successRedirect: 'profile',
successRedirect: '../../index.html'
}));
route.get('/profile', (req, res) => {
//Available to only logged in people
// Data is different (each user sees own profile)
// console.log(req)
if (req.user) {
res.json(req.user);
} else {
res.send("YOU ARE NOT LOGGED IN");
}
});
exports = module.exports = route;
Here is the screen shot when I run the project for Login page ..
Here is screen shot even user is login still displaying message first you must login.

Passport.js & Express Session - req.user undefined causing .isAuthenticted() to return false

I've spent more time than I'd like to admit scouring countless posts online that have the same problem as me, to no avail. The majority of solutions seemed to be things like not including
passReqToCallback: true in my LocalStrategy.
passport.serializeUser() and passport.deserializeUser() in my init file.
app.use(passport.initialize()) and app.use(passport.session()) in app.js.
Requiring and using app.use(cookieParser()) in app.js.
Passing cookie parser my secret key.
Adding proxy and cookie attributes to my expressSession variable in app.js.
Invoking req.login inside passport.authenticate within my page route.
And several other little tweaks I can't remember...
My login.js is as follows;
var LocalStrategy = require('passport-local').Strategy;
var User = require('../../models/user');
var bCrypt = require('bcrypt-nodejs');
module.exports = function(passport) {
passport.use('login', new LocalStrategy({passReqToCallback: true},
function(req, username, password, done) {
//Queries MongoDB For User
User.findOne({'username': username}, function(err, user) {
//In The Event Of An Error, Throw It
if (err) {
return done(err);
}
//Username Does Not Exist, Log Error, Callback, Flash Error Message
if (!user){
console.log('User: '+ username + ", does not exist.");
return done(null, false, req.flash('message', 'User Not found.'));
}
//User Exists, But Password Is Incorrect
if (!isValidPassword(user, password)){
console.log('Invalid Password');
return done(null, false, req.flash('message', 'Invalid Password')); // redirect back to login page
}
//If No Previous Error Conditions Are Met - Username/Password Are Correct
console.log("Validated User: " + username + ".");
//req.user = user;
return done(null, user);
}); //End of User.findOne()
}) //End of new LocalStrategy
); //End of passport.use()
/*
var isValidPassword = function(user, password){
return bCrypt.compareSync(password, user.password);
}
*/
//Passwords are not currently hashed in my DB, so ignore bcrypt for now.
var isValidPassword = function(user, password) {
return user.password == password;
}
}
My passport-init.js file
var login = require('./login');
var User = require('../../models/user');
module.exports = function(passport){
//Serialise User
passport.serializeUser(function(user, done) {
console.log("Serializing User: " + user.username + "\n" + user + ".");
done(null, user._id);
});
//De-Serialise User
passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user) {
console.log("Deserializing User: " + user.username + "\n" + user);
done(err, user);
});
});
//Setting up Passport Strategy for Login
login(passport);
}
My index.js file contains the POST Login route
/* POST Login Page*/
router.post('/login', passport.authenticate('login', {
successRedirect: '/dashboard',
failureRedirect: '/login',
failureFlash: true
}));
And dashboard.js contains all the routing for /dashboard/other-pages.
These ones are protected by the isAuthenticated function.
var express = require('express');
var router = express.Router();
var database = require('../public/javascripts/db-connect.js');
var isAuthenticated = function(req, res, next) {
console.log("User: " + req.user);
console.log("Authenticated?: " + req.isAuthenticated());
if (req.isAuthenticated()) {
return next();
} else {
res.redirect('/unauthorised');
}
}
module.exports = function(passport) {
//Routes /dashboard --> dashboard.pug
router.get('/', isAuthenticated, function(req, res, next) {
database.getData("busdata", function(err, data) {
if (err) {
console.error(err);
} else {
res.render('dashboard', {title: 'Dashboard', busdata: data});
}
});
});
//Routes /dashboard/journeys --> journeys.pug
router.get('/journeys', isAuthenticated, function(req, res, next) {
database.getData("journeydata", function(err, data) {
if (err) {
console.error(err);
} else {
res.render('journeys', {title: 'Journey Graphs', journeydata: data});
}
});
});
return router;
}
So when I run the app;
I check localhost:3000/dashboard and localhost:3000/dashboard/journeys. They correctly re-direct me to /unauthorised.
Navigate to /login.
Enter a correct username and password, the console then spits out:
Validated User: TomPlum. Meaning passport.use() reached return done(null, user)
Serialising User: TomPlum + the objects properties
POST /login 302 time ms
User: undefined from isAuthenticated
isAuthenticated? false
GET /dashboard 302 time ms
Deserialising User: TomPlum + the objects properties
I'm then redirected to /unauthorised as isAuthenticated() evaluates to false.
Why is req.user undefined? Should I be using a LocalStrategy if my MongoDB is not-local? (Amazon Atlas Server). Other forum posts have suggested it could be a cookie issue but I've included the relevant cookie-parser includes in my app.js file.
app.js is here in-case it's an order issue.
//Require Variables
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');
//Mongo DB Connection Settings
var dbConfig = require('./db'); //db.js contains DB URL
var mongoose = require('mongoose');
mongoose.connect(dbConfig.url); //dbConfig.url refers to the export in db.js
//Page Routing
//var index = require('./routes');
var users = require('./routes/users');
var dashboard = require('./routes/dashboard')(passport);
var app = express();
app.d3 = require('d3');
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public/images', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser('urban_sensing'));
app.use(express.static(path.join(__dirname, 'public')));
//app.use('/', index);
app.use('/dashboard', dashboard);
app.use('/users', users);
//Configuring Passport
var passport = require('passport');
var expressSession = require('express-session');
app.enable('trust-proxy');
app.use(expressSession({
secret: 'urban_sensing',
resave: true,
saveUninitialized: true,
proxy: true,
cookie: {
secure: true,
maxAge: 3600000
}
}));
app.use(passport.initialize());
app.use(passport.session());
//Flash Messaging For Passport
var flash = require('connect-flash');
app.use(flash());
//Initialize Passport
var initPassport = require('./public/javascripts/passport-init');
initPassport(passport);
var index = require('./routes/index')(passport);
app.use('/', index);
//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 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;
Some of the app.use(expressSession({..})); properties may currently be unnecessary as they've been added in an attempt to fix the issue.
Any help would be appreciated.
After too much time on this, turns out it was simply the order of app.js.
By moving
var dashboard = require('./routes/dashboard')(passport);
app.use('/dashboard', dashboard);
below all the passport configuration. It now works correctly. It seems that something wasn't initialised correctly during the routing of /dashboard when it was before the passport code.
Updated app.js
//Require Variables
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');
//Mongo DB Connection Settings
var dbConfig = require('./db'); //db.js contains DB URL
var mongoose = require('mongoose');
mongoose.connect(dbConfig.url); //dbConfig.url refers to the export in db.js
//Page Routing
//var index = require('./routes');
var users = require('./routes/users');
var app = express();
app.d3 = require('d3');
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public/images', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser('urban_sensing'));
app.use(express.static(path.join(__dirname, 'public')));
//app.use('/', index);
app.use('/users', users);
//Configuring Passport
var passport = require('passport');
var expressSession = require('express-session');
app.use(expressSession({
secret: 'urban_sensing',
resave: false,
saveUninitialized: true,
cookie: {
maxAge: 3600000 //1 Hour
}
}));
app.use(passport.initialize());
app.use(passport.session());
//Flash Messaging For Passport
var flash = require('connect-flash');
app.use(flash());
//Initialize Passport
var initPassport = require('./public/javascripts/passport-init');
initPassport(passport);
var dashboard = require('./routes/dashboard')(passport);
app.use('/dashboard', dashboard);
var index = require('./routes/index')(passport);
app.use('/', index);
//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 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;

express.js: show toastr message

I'm trying to get Toastr library to work in my ExpressJS app! I scaffolded the app with the yeoman 'standard' Express Generator...
I've required the lib express-toastr and did the following:
in app.js:
const cookieParser = require('cookie-parser');
const session = require('express-session');
const flash = require('connect-flash');
const toastr = require('express-toastr');
app.use(cookieParser());
app.use(session( {secret: 'xxx', saveUninitialized: true, resave: true} ));
app.use(flash());
app.use(toastr());
in index.js
const express = require('express');
const router = express.Router();
const httpntlm = require('httpntlm');
router.post('/', function (req, res, next) {
// parse inputs
let user = req.body.user || "";
let password = req.body.password || "";
// save in session
req.session.user = {user: user, password: password};
// appropriate response to login attempt
if (!req.session.user) {
res.status(401).send();
}
else {
req.toastr.success('Successfully logged in.', "You're in!");
res.render('groups', {
req: req
});
}
});
module.exports = router;
In index.jade
#{req.toastr.render()}
I'm loading these files in my <head> section:
link(rel='stylesheet', href='//cdnjs.cloudflare.com/ajax/libs/toastr.js/2.0.2/css/toastr.min.css')
script(src='/components/jquery/dist/jquery.min.js')
script(src='//cdnjs.cloudflare.com/ajax/libs/toastr.js/2.0.2/js/toastr.min.js')
Nothing is showing. What am I missing???
-- UPDATE! --
Here is my complete app.js file. I now try to use express-flash and making a dedicated route for showing a flash message. Still not working. Please help!
'use strict';
const express = require('express');
const path = require('path');
const favicon = require('serve-favicon');
const logger = require('morgan');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const expressSanitizer = require('express-sanitizer');
const login = require('./routes/login');
const apply = require('./routes/apply');
const admin = require('./routes/admin');
var session = require('express-session');
var flash = require('express-flash');
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')));
app.use(session({
cookie: { maxAge: 60000 },
store: new session.MemoryStore,
saveUninitialized: true,
resave: 'true',
secret: 'secret'
}));
app.use(flash());
// Route that creates a flash message using the express-flash module
app.all('/express-flash', function( req, res ) {
req.flash('success', 'This is a flash message using the express-flash module.');
res.redirect(301, '/');
});
// sanitize inputs
app.use(expressSanitizer());
app.use('/', apply);
app.use('/apply', apply);
app.use('/login', login);
app.use('/admin', admin);
// 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 using this middleware in your app.js, I found this here
app.use(function (req, res, next)
{
res.locals.toasts = req.toastr.render()
next()
});
and then access locals in your view as follows:
#{toasts}
This worked for me.
So I am not familiar with your syntax in your index.jade file(!=). What does it do? If you change that line in your index to #{req.toastr.render()} it should work.

It doesn't validate when If I write things to form inputs are even correct. It gives all errors everytime

I m learning from fast record on youtube. calls "Learn NodeJS building 10 projects". he is doing that at 15. video. Well this is my first post here. dont yell me cuz its my first message here. and please use easy english :) salute from turkey.
///THIS IS THE APP.JS
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var expressValidator = require('express-validator');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var bodyParser = require('body-parser');
var multer = require('multer');
var flash = require('connect-flash');
var mongo = require('mongodb');
var mongoose = require('mongoose');
var db = mongoose.connection;
var routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
//handle file uploads multer
//app.use(multer({dest:'./uploads'}));
var upload = multer({ dest: './uploads' });
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
// handle express-session
app.use(session({
secret:'secret',
saveUninitialized: true,
resave:true
}));
// passport
app.use(passport.initialize());
app.use(passport.session());
// express-validator
app.use(expressValidator({
errorFormatter: function(param, msg, value) {
var namespace = param.split('.')
, root = namespace.shift()
, formParam = root;
while(namespace.length) {
formParam += '[' + namespace.shift() + ']';
}
return {
param : formParam,
msg : msg,
value : value
};
}
}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
// connect-flash
app.use(flash());
// express-messages
app.use(function (req, res, next) {
res.locals.messages = require('express-messages')(req, res);
next();
});
app.use('/', routes);
app.use('/users', users);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
------------------------------
THIS IS THE USERS.JS
------------------------------
var express = require('express');
var router = express.Router();
/* GET users listing. */
router.get('/', function(req, res, next) {
res.send('respond with a resource');
});
router.get('/yenihesap', function(req, res, next) {
res.render('yenihesap',{
'title': 'Yeni Hesap Aç'
});
});
router.get('/giris', function(req, res, next) {
res.render('giris',{
'title': 'Giriş Yap'
});
});
router.get('/sifremiunuttum', function(req, res, next) {
res.render('sifremiunuttum',{
'title': 'Şifremi Unuttum'
});
});
router.post('/yenihesap', function(req, res, next){
// get form values
var name = req.body.name;
var lastname = req.body.lastname;
var email = req.body.email;
var password = req.body.password;
var password2 = req.body.password2;
// form validation
req.checkBody('name', 'Lütfen isminizi giriniz').notEmpty();
req.checkBody('lastname', 'Lütfen soyadınızı giriniz').notEmpty();
req.checkBody('email', 'Lütfen email adresinizi giriniz').notEmpty();
req.checkBody('email', 'Bu bir email adresi değil!').isEmail();
req.checkBody('password', 'Lütfen şifrenizi giriniz').notEmpty();
req.checkBody('password2', 'Şifreniz eşleşmiyor!').equals(req.body.password);
// check for errors
var errors = req.validationErrors();
if(errors){
res.render('yenihesap',{
errors: errors,
name: name,
lastname: lastname,
email: email,
password: password,
password2: password2
});
}else{
var newUser = new User({
name: name,
lastname: lastname,
email: email,
password: password
});
// create user
//User.createUser(newUser, function(err, user){
// if(err) throw err;
// console.log(user);
//});
//succes message
req.flash('success', 'Başarıyla kayıt oldunuz');
res.location('/');
res.redirect('/');
}
});
module.exports = router;
this is the jade file
when even i full up to input forms correctly, all errors that i have. i dont understand why
I found the problem. Its about the multer. first of all it wasnt work with that code at the beggining
//handle file uploads multer
app.use(multer({dest:'./uploads'}));
the multer was giving me error and changed it to that
//handle file uploads multer
var upload = multer({ dest: './uploads' });
and this time multer had me this question problem that body parser wasnt work. so I changed to that. and it fixed my problem. I found it another question on stackover: typeerror: app.use() requires middleware function
//handle file uploads multer
app.use(multer({dest:'./uploads/'}).single('singleInputFileName'));
I m happy to joined this site. Its obviously perfect that people help each other. see you on next problems :)

Browser doesn't show index page made by index.js and index.jade on Node.js

I'd like to show index page by index.js and index.jade on Node.js, however browser returns the page only show index.html as attached picture.
I set the index.js as routes as following, thus I think the root path should return index page.
var routes = require('./routes/index');
app.use('/', sessionCheck, routes);
The following is my present code. Could you tell me what is the problem?
###app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');
var routes = require('./routes/index');
var users = require('./routes/users');
var login = require('./routes/login');
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(__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')));
app.use(session({
secret: 'keyboard cat',
resave: false,
saveUninitialized: false,
cookie: {
maxAge: 30 * 60 * 1000 // 30min.
}
}));
var sessionCheck = function(req, res, next) {
if (req.session.user) {
next();
} else {
res.redirect('/login');
}
};
app.use('/login', login);
app.use('/', routes);
app.use('/users', users);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
###routes/index.js
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
module.exports = router;
###views/index.jade
extends layout
block content
h1= title
p Welcome to #{title}
I've found the problem.
Becuase I set the root directory '/public', I could not access index.js.Thank you for you kindeness.
app.use(express.static(path.join(__dirname, 'public')));

Resources