Server side code:
var User = require("./models/user");
var express = require('express'),
app = express(),
Account = require("./models/account"),
mongoose = require('mongoose'),
passport = require("passport"),
basicAuth = require('basic-auth'),
bodyParser = require("body-parser"),
LocalStrategy = require("passport-local"),
passportLocalMongoose = require("passport-local-mongoose"); //libraries
mongoose.connect("mongodb://localhost/test");
app.set('view engine', 'ejs'); //using engine of ejs file
app.use(bodyParser.urlencoded({extended: true}));
app.use(require("express-session")({
secret: "kiss my ass",
resave: false,
saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());
passport.use(new LocalStrategy(Account.authenticate()));
passport.serializeUser(Account.serializeUser());
passport.deserializeUser(Account.deserializeUser());
// AUTH Routes
//create account success
app.get('/success', function (req, res) {
res.render('success');
});
// deleteUser form
app.get("/delete", function(req, res, next) {
res.render("deleteuser");
});
app.get("/viewall", function(req, res, next) {
res.render("viewall");
});
//view all User form
app.get('/view', function (req, res) {
console.log('getting all user');
Account.find({})
.exec(function(err, results) {
if(err) {
res.send('error has occured');
}else{
console.log(results);
res.json(results);
}
});
});
app.get('/viewall/:id', function (req, res) {
console.log('getting one user');
Account.findOne({
_id:req.params.id
})
.exec(function(err, account) {
if(err) {
res.send('error occured');
}else{
console.log(account);
res.json(account);
}
})
})
// LOGIN for user
// render login form
app.get("/", function(req, res) {
res.render("login");
});
//login for user
//middleware
app.post("/login", passport.authenticate("local", {
successRedirect: "http://localhost:8082/viewImage.html",
failureRedirect: "http://localhost:8081/error"
}), function(req, res) {
});
//logout from basicauth
app.get('/logout', function (req, res) {
res.set('WWW-Authenticate', 'Basic realm=Authenticate Required');
return res.sendStatus(401);
// res.send("<a href='/login'>Show Users</a>");
});
//basicauth for admin login
var auth = function (req, res, next) {
function unauthorized(res) {
res.set('WWW-Authenticate', 'Basic realm=Authenticate Required');
return res.send(401);
};
var user = basicAuth(req);
if (!user || !user.name || !user.pass) {
return unauthorized(res);
};
if (user.name === 'admin' && user.pass === 'admin123') {
return next();
} else {
return unauthorized(res);
};
};
//LOGIN for admin
//render login form
app.get("/register", auth, function(req, res) {
res.render("register");
});
// register post
app.post("/register", function(req,res){
Account.register(new Account({username: req.body.username}), req.body.password, function(err, user){
if(err){
console.log(err);
return res.render('/register');
}
passport.authenticate("local")(req, res, function(){
res.redirect("/success");
});
});
});
app.listen(8081, function () {
console.log('ImageViewer listening on port 8081!');
});
JS code:
$scope.delete = function (data) {
if (confirm('Do you really want to delete?')){
$window.location.reload();
$http['delete']('/viewall/' + data._id).success(function() {
$scope.users.splice($scope.users.indexOf(data), 1);
});
}
};
html code:
<tr ng-repeat="user in users | filter:searchBox | orderBy:'+username'">
<td>{{user._id}}</td>
<td>{{user.username}}</td>
<td><button class="btn btn-primary" ng-click="delete(user)">Delete</button></td>
This is the error i got:
DELETE
XHR
http://localhost:8081/viewall/5784919136ccb93d0ba78d4b [HTTP/1.1 404 Not Found 8ms]
But when i run the url of http://localhost:8081/viewall/5784919136ccb93d0ba78d4b and it does give me the data:
{"_id":"5784919136ccb93d0ba78d4b","username":"qs","__v":0}
Anybody can help me? don't know what's with the error404 when i'm able to get the data.
You have no route for '/viewall/:id' with DELETE verb. So you should add route with DELETE verb. like
app.delete('/viewall/:id',function(req,res){
// rest of code here
// assume your model name Account
Account.remove({ _id: req.params.id },function(err,doc) {
if(err) {
return res.status(400).send({msg: 'Error occurred during delete account'});
}
return res.status(200).send({msg: 'Successfully deleted'});
});
}
and you should reload after success in your angular controller. like
$http['delete']('/viewall/' + data._id).then(function(response) {
$scope.users.splice($scope.users.indexOf(data), 1);
$window.location.reload();
});
Related
my app.js not working as i think. so, after i register for a new one, it will send to my MongoDB and take me directly to the page2 but it is taking back to the home page and when i type in and click on login, it will have the error "This site can’t be reached" on localhost:8080/processLogin. im not sure how to fix them. i think errors are on function checkLogin(req, res, user, password) and app.post('/processReg', function(req, res)
app.js
var express = require('express'),
handlebars = require('express-handlebars').create({ defaultLayout: 'main' }),
cookieParser = require('cookie-parser'),
sessions = require('express-session'),
bodyParser = require('body-parser'),
https = require('https'),
fs = require('fs'),
md5 = require('md5'),
mongoose = require('mongoose'),
credentials = require('./credentials'),
Users = require('./models/uCredentials.js');
// load env variables
const dotenv = require("dotenv");
dotenv.config();
var app = express();
//db connection
mongoose
.connect(process.env.MONGO_URI, {
useUnifiedTopology: true,
useNewUrlParser: true,
})
.then(() => console.log("DB Connected"));
mongoose.connection.on("error", (err) => {
console.log(`DB connection error: ${err.message}`);
});
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser(credentials.cookieSecret));
app.use(sessions({
resave: true,
saveUninitialized: false,
secret: credentials.cookieSecret,
cookie: { maxAge: 3600000 },
}));
app.engine('handlebars', handlebars.engine);
app.set('view engine', 'handlebars');
app.set('port', process.env.PORT || 3100);
app.get('/', function(req, res) {
res.render('login');
});
function checklogin(req, res, user, password) {
//implementation of this function
Users.findOne({ uname: user }, function(err, user) {
if (err) {
console.log(err);
res.send({ 'message': 'Login successfully!' });
} else {
res.send({ 'message': 'Username or password do not match our records. Please try again or register if you are a new user!' });
}
});
};
app.post('/processLogin', function(req, res) {
//Determine if user is registering
if (req.body.buttonVar == 'login') {
checklogin(req, res, req.body.uname.trim(), req.body.pword.trim())
} else {
res.redirect(303, 'register');
}
});
app.post('/processReg', function(req, res) {
//implement this end point
if (req.body.pword.trim() == req.body.pword2.trim()) {
const user = new Users({ uname: req.body.uname, pass: req.body.pword });
console.log('Creating new user ', req.body);
user.save((err, toDB) => {
if (err) {
return res.status(400).json({ error: err });
}
res.status(200).json({ user: toDB });
});
res.redirect(303, 'page2');
} else {
res.render('register', { message: 'The two passwords are not the same !' });
}
});
app.get('/home', function(req, res) {
if (req.session.userName) {
res.render('home');
} else {
res.render('login', { message: 'Please login to access the home page' });
}
});
app.get('/page2', function(req, res) {
if (req.session.userName) {
res.render('page2');
} else {
res.render('login', { message: 'Please login to access the second page' });
}
});
app.get('/register', function(req, res) {
res.render('register');
});
app.get('/logout', function(req, res) {
delete req.session.userName;
res.redirect(303, '/');
});
app.listen(app.get('port'), function() {
console.log('Express started on http://localhost:' + app.get('port') + '; press Ctrl-C to terminate');
});
process.on('unhandledRejection', error => {
// Will print "unhandledRejection err is not defined"
console.log('unhandledRejection', error.message);
});
callback logic for findOne query is wrong. check this out async/await For checkLoging function try using this:
async function checklogin(req, res, user, password) {
try {
//implementation of this function
const user = await Users.findOne({ uname: user }).exec();
if (!user) {
res.send({ 'message': 'Username or password do not match our records. Please try again or register if you are a new user!' });
}
res.send({ 'message': 'Login successfully!' });
} catch (err) {
console.log(err.message)
}
};
If you don't want to use Async/await (which I recomend for mongodb queries) you can use this:
function checklogin(req, res, user, password) {
//implementation of this function
Users.findOne({ uname: user }, function(err, user) {
if (err) {
console.log(err);
res.send({ 'message': 'Username or password do not match our records. Please try again or register if you are a new user!' });
}
res.send({ 'message': 'Login successfully!' });
});
};
Currently I'm working on a little project for a dummy login/register page and now I want to add a page that is only accessible when you're logged in. So the question is how do I make a session or cookie and retrieve them? And how do I block not logged in users.
I'm currently using this code for the 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 expressSession = require('express-session');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var AuthTokenStrategy = require('passport-auth-token').Strategy;
require('./models');
var User = mongoose.model('User')
mongoose.connect('mongodb://localhost:27017/my-data', { useNewUrlParser: true, useUnifiedTopology: true })
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
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')));
passport.use(new LocalStrategy({
usernameField: "key"
}, function(key, next) {
User.findOne({
key: key
}, function(err, user) {
if (err) return next(err);
if (!user) {
return next({message: 'Key incorrect'})
}
next(null, user);
})
}));
passport.serializeUser(function (user, next) {
next(null, user._id)
})
passport.deserializeUser(function (id, next){
User.findById(id, function (err, user) {
next(err, user);
});
});
app.use(passport.initialize());
app.use(passport.session());
app.use(expressSession({
secret: 'aksndklajsdjicpwoemcklnaiohdandascopkqpowdmklasmdiojqwndjkasndosiqjwdklnasaksndklajsdjicpwoemcklnaiohdandascopkqpowdmklasmdiojqwndjkasndosiqjwdklnas'
}))
app.get('/', function(req, res, next){
res.render('index', {title: 'MySite'})
});
app.get('/main', function(req, res, next){
res.render('main')
});
app.get('/login', function(req, res, next){
res.render('login')
});
app.post('/signup', function(req, res, next){
User.findOne({
key: req.body.key
}, function (err, user) {
if (err) return next(err)
if (user) return next({message: 'This client exists'})
let newUser = new User({
key: req.body.key
});
newUser.save(function(err) {
if (err) return next(err);
res.redirect('/main');
});
console.log(req.body)
});
});
app.post('/login', async (req, res, next) => {
const key = req.body.key;
//const ip = req.header('x-forwarded-for') || req.connection.remoteAddress;
//console.log(ip);
if (!key) return res.status(401).json({ err: 'Key not provided' });
const User = mongoose.model('User');
const user = await User.findOne({ key }).exec();
if (!user) return res.status(401).json({ err: 'Invalid Key' });
res.redirect('/main');
});
// 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;
Try do add this middleware to protected route:
function isAuthenticated(req,res,next){
if(req.isAuthenticated()){ // will return true if user is logged in
next();
} else{
res.redirect("/login");
}
}
app.get('/protectedPath',isAuthenticated, function(req,res) {
//protected content
);
I am trying to make a get request with ajax, it doesn't seem to run the code in my NodeJS /tools route, maybe someone can enlighten me. I am looking to run a script from nodeJS from an AJAX request. xhr GET request doesn't seem to work with to initiate the that console log in the nodejs route.
These are my routes.
const express = require('express');
const router = express.Router();
const User = require('../models/user.js');
const mid = require('../middleware');
const axios = require('axios');
// Home Routes
router.get('/', (req, res, next) => {
res.render('index');
});
// About Routes
router.get('/about', (req, res, next) => {
res.render('about', {title : '| About'});
});
// Tools Routes
router.get('/tools', (req, res, next) => {
console.log("ajax request went through!");
});
router.post('/tools', (req, res, next) => {
var domain = req.body.domain;
canYouDigIt(domain);
});
router.get('/map', (req, res, next) => {
res.render('map');
});
// Login Routes
router.get('/login', mid.loggedOut, (req, res, next) => {
res.render('login', {title : '| Log in'});
});
router.post('/login', (req, res, next) => {
if ( req.body.email && req.body.password) {
User.authenticate(req.body.email, req.body.password, function(error, user){
if (error || !user) {
var err =new Error('Wrong email or password.');
err.status = 401;
return next(err);
} else {
req.session.userId = user._id;
return res.redirect('/profile');
}
});
} else {
var err =new Error('Email and password are required!');
err.status = 401;
return next(err);
}
});
// Logout Routes
router.get('/logout', (req, res, next) => {
if (req.session){
// Delete Session
req.session.destroy(function(err) {
if(err) {
return next(err);
} else {
return res.redirect('/');
}
});
}
});
// Registration Routes
router.get('/registration', mid.loggedOut, (req, res, next) => {
res.render('registration', {title : '| Registration'});
});
router.post('/registration', (req, res, next) => {
// Check if all fields are filled
if (req.body.userName && req.body.password && req.body.confirmPassword && req.body.firstName && req.body.lastName && req.body.email) {
// Confirm Password is the same
if ( req.body.password != req.body.confirmPassword) {
const err = new Error ("Passwords don't match!");
err.status = 400;
return next(err);
};
const userData = {
userName: req.body.userName,
password: req.body.password,
firstName: req.body.firstName,
lastName: req.body.lastName,
email: req.body.email
};
// Use schema 'create' method to insert document into Mongo
User.create(userData, (error, user) => {
if (error) {
return next(error);
} else {
req.session.userId = user._id;
return res.redirect('/profile');
}
});
} else {
const err = new Error("All Fields Required.");
err.status = 400;
return next(err);
}
});
module.exports = router;
This is my html/pug calling the route
section(id="digToolWrapper")
form( id="digToolInput" )
ul
li #[input(id="digTool" name="domain" type="text" placeholder="Can you dig it?")]#[input(id="whois" value="whois" type="button" onclick="digIt()")]
This is my ajax request
function digIt() {
var xhr = new XMLHttpRequest();
var domain = document.getElementById("digTool").value;
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log(domain);
}
};
xhr.open('GET', '/tools', true);
console.log(domain);
xhr.send();
};
App.js file
const express = require('express');
const session = require('express-session');
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');
const path = require('path');
const mongoose = require('mongoose');
const MongoStore = require('connect-mongo')(session);
const axios = require('axios');
const app = express();
// Mongodb connection
mongoose.connect("mongodb://localhost:27017/nymadic", { useNewUrlParser: true });
const db = mongoose.connection
// Mongo error
db.on('error', console.error.bind(console, 'connection error:'));
// Use sessions for tracking logins
app.use(session({
secret: 'keyboard cat!',
resave: true,
saveUninitialized: false,
// This stores sessions in the Mongo DB so the server doesnt become overloaded
store: new MongoStore({
mongooseConnection: db
})
}));
// Make user ID available in template
app.use(function (req, res, next){
res.locals.currentUser = req.session.userId;
next();
});
// Body Parser and Cookie Parser
app.use(bodyParser.urlencoded({ extended:false }));
app.use(cookieParser());
// Static Files
app.use(express.static(__dirname + '/public'));
// Pug Render Engine
app.set('view engine', 'pug');
// Routes
const mainRoutes = require('./routes');
const profileRoutes = require('./routes/profile');
const wikiRoutes = require('./routes/wiki');
app.use(mainRoutes);
app.use('/profile', profileRoutes);
app.use('/wiki', wikiRoutes);
app.listen(8080, () => {
console.log('Nodejs is running on port 8080...');
});
I'm trying to add user-login module to an existing app in node. It is using separate route files for each module and one main route file to use all the child routes which is ultimately used in server.js
When I try to pass passport instance to the user route, it gives me error as passport is not defined. Here is my app code and structure:
app
views
user
index.ejs
login.ejs
signup.ejs
profile.ejs
routes
docs
index.js
user
index.js
index.js
config
passport.js
server.js
server.js
const express = require('express')
const app = express()
const path = require('path')
const bodyParser = require('body-parser')
const cookieParser = require('cookie-parser')
const passport = require('passport')
const flash = require('connect-flash')
const session = require('express-session')
const routes = require('./routes/')
const port = process.env.PORT || 3000;
app.use(express.static(path.join(__dirname, 'public')));
require('./config/passport')(passport);
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(cookieParser());
app.use(bodyParser.json());
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
app.use(session({ secret: '********' }));
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
app.use('/', routes)(app,passport);
const server = app.listen(port, function(){
console.log('Server listening on port '+port);
});
config/passport.js
var LocalStrategy = require('passport-local').Strategy;
const sql = require('mssql')
const bcrypt = require('bcrypt-nodejs')
module.exports = function(passport) {
passport.serializeUser(function(user, done) {
done(null, user);
});
passport.deserializeUser(function (username, done) {
done(null,username);
});
passport.use('local-signup', new LocalStrategy({
usernameField : 'email',
passwordField : 'password',
passReqToCallback : true
},
function(req, email, password, done) {
process.nextTick(function() {
var strSQL = "SELECT count(id) as uCount FROM <tbl> WHERE username = '"+email+"'";
var cb1 = function(err,recordset){
if(recordset[0].uCount>0){
return done(null, false, req.flash('signupMessage', 'That email is already taken.'));
} else{
var strSQL1 = "INSERT INTO <tbl>(username, password) VALUES('"+email+"','"+generateHash(password)+"')";
var cb2 = function(err,recordset){
return done(null, recordset,req.flash('signupMessage', 'Email registered successfully.'));
};
executeQuery(strSQL1,'INSERTION','<tbl>',cb2);
}
};
executeSelection(strSQL,'SELECTION','<tbl>',cb1);
});
}));
passport.use('local-login', new LocalStrategy({
usernameField : 'email',
passwordField : 'password',
passReqToCallback : true
},
function(req, email, password, done) {
var strSQL = "SELECT a.count, id, username, password FROM <tbl> c , (SELECT COUNT(dbid) count FROM <tbl> b WHERE b.username = '"+email+"' ) a WHERE c.username = '"+email+"'";
var cb1 = function(err,recordset){
if(recordset[0].uCount <= 0){
return done(null, false, req.flash('loginMessage', 'No user found.'));
}
if (!validPassword(password,recordset[0].password))
return done(null, false, req.flash('loginMessage', 'Oops! Wrong password.'));
return done(null, recordset[0]);
};
executeSelection(strSQL,'SELECTION','<tbl>',cb1);
}));
};
executeSelection = function(strSQL, operationType, tableName, cb){
var request = new sql.Request(connection);
request.query(strSQL,function(err,recordset) {
if(err){
logger.error('ERROR in '+operationType+' ON '+tableName+': '+err);
}
logger.info(operationType+' ON '+tableName+' successful!');
cb(err,recordset);
});
};
executeQuery = function(strSQL, operationType, tableName, cb,validateClient) {
var request = new sql.Request(connection);
request.query(strSQL,function(err, recordset) {
if(err){
logger.error('ERROR in '+operationType+' ON '+tableName+': '+err);
}
logger.info(operationType+' ON '+tableName+' successful!');
if(cb){
cb(validateClient);
}
});
};
generatePasswordHash = function(password) {
return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);
};
validatePassword = function(curPass, dbPass) {
return bcrypt.compareSync(curPass, dbPass);
};
routes/index.js
const mainroute = require('express').Router()
/* ---- other existing routes included ---- */
const r_docs = require('./docs')
const r_user = require('./user') /*my custom route*/
/* ---- all other routes ---- */
mainroute.use('/docs', r_docs);
mainroute.use('/user', r_user)(app, passport); /*my custom route*/
mainroute.get('/', function(req, res){
res.render('home');
});
module.exports = function(app, passport){
mainroute;
}
routes/user/index.js
const express = require('express')
const router = express.Router()
router.get('/', function(req, res) {
res.render('user/index.ejs');
});
router.get('/login', function(req, res) {
res.render('user/login.ejs', { message: req.flash('loginMessage') });
});
// process the login form
router.post('/login', passport.authenticate('local-login', {
successRedirect : '/profile',
failureRedirect : '/login',
failureFlash : true
}));
router.get('/signup', function(req, res) {
res.render('user/signup.ejs', { message: req.flash('signupMessage') });
});
router.post('/signup', passport.authenticate('local-signup', {
successRedirect : '/profile',
failureRedirect : '/signup',
failureFlash : true
}));
router.get('/profile', isLoggedIn, function(req, res) {
res.render('user/profile.ejs', {
user : req.user
});
});
router.get('/logout', function(req, res) {
req.logout();
res.redirect('/');
});
function isLoggedIn(req, res, next) {
if (req.isAuthenticated())
return next();
res.redirect('/');
}
module.exports = function(app, passport) {
router;
}
Please suggest what am I doing wrong here. Thanks
You should wrap your main and user routes to run their logic when you call them and at end return prepared route:
routes/index.js
module.exports = function(app, passport) {
const mainroute = require('express').Router()
/* ---- other existing routes included ---- */
const r_docs = require('./docs');
const r_user = require('./user'); /*my custom route*/
/* ---- all other routes ---- */
mainroute.use('/docs', r_docs);
mainroute.use('/user', r_user)(app, passport); /*my custom route*/
mainroute.get('/', function(req, res) {
res.render('home');
});
return mainroute;
};
routes/user/index.js
module.exports = function(app, passport) {
const express = require('express');
const router = express.Router();
router.get('/', function(req, res) {
res.render('user/index.ejs');
});
router.get('/login', function(req, res) {
res.render('user/login.ejs', {
message: req.flash('loginMessage')
});
});
// process the login form
router.post('/login', passport.authenticate('local-login', {
successRedirect: '/profile',
failureRedirect: '/login',
failureFlash: true
}));
router.get('/signup', function(req, res) {
res.render('user/signup.ejs', {
message: req.flash('signupMessage')
});
});
router.post('/signup', passport.authenticate('local-signup', {
successRedirect: '/profile',
failureRedirect: '/signup',
failureFlash: true
}));
router.get('/profile', isLoggedIn, function(req, res) {
res.render('user/profile.ejs', {
user: req.user
});
});
router.get('/logout', function(req, res) {
req.logout();
res.redirect('/');
});
function isLoggedIn(req, res, next) {
if (req.isAuthenticated())
return next();
res.redirect('/');
}
return router;
};
You need to require it at the top of your user/index.js. Simply:
var passport = require('passport');
Then to make sure the user is authenticated:
router.get('/some/path', isLoggedIn, function(req, res) {
var user = req.user;
});
function isLoggedIn(req, res, next) {
if (req.isAuthenticated())
return next();
res.redirect('/');
}
In my app.js I do this
app.use(function(req, res, next){
if(!req.user){
return res.redirect('/login_');
}
next();
})
I don't see anything wrong and in route/index.js I do
router.get('/login_', function(req, res) {
res.render('login', { user : req.user });
});
But I got an error. I know this is caused by the request is not ended but what's wrong with my code above? clueless with this error.
Full code of route/index.js
var express = require('express');
var passport = require('passport');
var Account = require('../models/account');
var router = express.Router();
var multer = require('multer');
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'public/uploads')
}
})
var upload = multer({ storage: storage })
var Photo = require('../models/photos');
router.get('/', function(req, res, next) {
if(req.user){
res.redirect('/'+req.user.username+'/screen');
}else{
res.redirect('/login_');
}
});
router.get('/:username/screen', function(req, res, next) {
res.render('screen', { user : req.user });
});
router.get('/:username', function(req, res, next) {
var excludes = ["/login_", "/register_","/logout_"];
if (excludes.indexOf(req.originalUrl) > -1){
return next();
}else{
res.render('upload_photo');
}
});
router.post('/:username', upload.any(), function(req, res, next) {
var excludes = ["/login_", "/register_","/logout_"];
if (excludes.indexOf(req.originalUrl) > -1){
return next();
}else{
var photo = new Photo({
photo:req.files[0].filename,
caption:req.body.caption
});
photo.save(photo);
res.sendStatus(200);
}
});
router.get('/:username/manager', function(req, res, next) {
Photo.getAllPhotos(function(err,result){
var headers = req.headers.host;
var pathname = '128.199.128.108:3000';
if(headers.indexOf('localhost') > -1){
pathname = 'localhost:3000'
}
res.render('manager',{pathname:pathname,photos:result});
});
});
//* passport for register/login_ *//
router.get('/register_', function(req, res) {
res.render('register', { });
});
router.post('/register_', function(req, res) {
Account.register(new Account({ username : req.body.username }), req.body.password, function(err, account) {
if (err) {
return res.render('register', { account : account });
}
passport.authenticate('local')(req, res, function () {
res.redirect('/');
});
});
});
router.get('/login_', function(req, res) {
res.render('login', { user : req.user });
});
router.post('/login_', passport.authenticate('local'), function(req, res) {
res.redirect('/');
});
router.get('/logout_', function(req, res) {
req.logout();
res.redirect('/login_');
});
module.exports = router;
You are printing something before this line.
Either trace that, or instruct your server to cache some of the output to the user.
(if the server does not display anything to the user, headers can be sent, even if code tries to print something before)
However that is general knowledge, not familiar with node.js