I've created a cart object, which can store the products in a cart. The problem is before an item is put into the cart it is undefined. How do I make the cart defined even when nothing is in it during the session? I'm using ejs.
Here is my Error
/home/ubuntu/workspace/views/partials/header.ejs:37
35| </li>
36| <li>
>> 37| <a href="cart" class="navport"><span
class="badge"><%= session.cart.totalQty || 0%></span></a>
38| </li>
39| </ul>
40|
Cannot read property 'totalQty' of undefined
App.js
var express = require("express");
var app = express();
var mongoose = require("mongoose"),
User = require("./models/user"),
bodyParser = require("body-parser"),
ejs = require("ejs"),
passport = require("passport"),
LocalStrategy = require("passport-local"),
localMongoose = require("passport-local-mongoose"),
session = require("express-session"),
MongoStore = require("connect-mongo")(session),
Cart = require("./models/cart"),
Clothes = require("./models/clothes");
mongoose.connect("mongodb://localhost/bitchinvintage");
app.set("view engine", "ejs");
app.use(express.static(__dirname + "/public"));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(session({
secret: "random dogga",
resave: false,
saveUninitialized: false,
store: new MongoStore({mongooseConnection: mongoose.connection}),
cookie: {maxAge: 180 * 60 * 1000}
}));
app.use(passport.initialize());
app.use(passport.session());
passport.use(new LocalStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
app.use(function (req, res, next) {
res.locals.login = req.isAuthenticated();
res.locals.session = req.session;
next();
});
app.get("/", function(req, res){
res.render("landing");
});
// Clothes Routes
app.get("/clothes", function(req, res){
// Get all campgrounds from DB
Clothes.find({}, function(err, clothes){
if(err){
console.log(err);
} else {
res.render("clothes",{clothes:clothes});
}
});
});
app.get("/clothes/new", function(req, res){
res.render("new");
});
app.post("/clothes", function(req, res){
var name = req.body.name;
var overlay = req.body.overlay;
var price = req.body.price;
var image = req.body.image;
var newClothes = {name: name, image: image, price: price, overlay: overlay}
Clothes.create(newClothes, function(err, newlyCreated){
if(err){
console.log(err);
} else{
res.redirect("/clothes");
}
});
});
// ------------------
// Register Routes
app.get("/register", function(req, res){
res.render("register");
});
app.post("/register", function(req, res){
var newUser = new User({username: req.body.username});
User.register(newUser, req.body.password, function(err, user){
if (err){
console.log(err);
return res.render("register");
}
passport.authenticate("local")(req, res, function(){
res.redirect("/");
})
})
});
// -----------
// Login Routes
app.post("/login", passport.authenticate("local", {
successRedirect: "/",
failureRedirect: "/register"
}), function(req, req){
});
// Cart Routes
app.get("/add-to-cart/:id", function(req, res, next){
var productId = req.params.id;
var cart = new Cart(req.session.cart ? req.session.cart : {});
console.log("works");
Clothes.findById(productId, function(err, clothes){
if(err){
return res.redirect("/");
}
cart.add(clothes, productId);
req.session.cart = cart;
console.log(req.session.cart);
res.redirect("/clothes");
});
});
// ------------
app.get("/account", isLoggedIn, function(req, res){
});
app.get("/*", function(req, res){
res.render("error");
});
app.listen(process.env.PORT, process.env.IP, function(){
console.log("Vintage server Starting...")
});
function isLoggedIn(req, res, next) {
if (req.user) {
next();
} else {
res.redirect("/account");
}
}
models/cart.js
This is the cart Object
module.exports = function Cart(oldCart) {
this.items = oldCart.items || {};
this.totalQty = oldCart.totalQty || 0;
this.totalPrice = oldCart.totalPrice || 0;
this.add = function(item, id) {
var storedItem = this.items[id];
if (!storedItem){
storedItem = this.items[id] = {item: item, qty: 0, price: 0}
}
storedItem.qty++;
storedItem.price = storedItem.item.price * storedItem.qty;
this.totalQty++;
this.totalPrice += storedItem.price;
}
this.generateArray = function() {
var arr = [];
for (var id in this.items) {
arr.push(this.items[id]);
}
return arr;
}
};
header.ejs
This is the HTML where I'm trying to list the total amount in the cart on the navbar
<li>
<a href="cart" class="navport"><span class="badge"><%=
session.cart.totalQty || 0%></span></a>
</li>
</ul>
var Cart = require('../models/cart');
(path for cart model)
did you include this line in your route ? because of that you are getting cart it is undefined error. please make sure that you have included above line in your route file. when you create a cart object this line will help you refer the cart model.
I've faced the same issue while loading the index template. Can you check if session.cart is available before rendering shopping-cart quantity? I added simple if condition like below and it worked for me.
<% if(session.cart) { %>
<span class="badge"><%= session.cart.totalQty %></span>
<% } %>
Related
I am trying to run my app.js locally on my editor, It works in the editor when I try to run it on a browser it loads the first page when I click on a link to enter the site, I get an error UnhandledPromiseRejectionWarning MongoTimeoutError server selection timed out after 30000 ms. I am new at this, this is actually part of a course through udemy. I have searched on google, reddit threads etc. Can't seem to figure this out. Please don't laugh if this is a dumb question. If you need more code let me know I will provide it.
Thanks
here is my app.js
var express = require("express"),
app = express(),
bodyParser = require("body-parser"),
mongoose = require("mongoose"),
flash = require("connect-flash"),
passport = require("passport"),
LocalStrategy = require("passport-local"),
methodOverride = require("method-override"),
Campground = require("./models/campground"),
Comment = require("./models/comment"),
User = require("./models/user")
// seedDB = require("./seeds")
// mongoose.Promise = global.Promise
//requiring routes
var commentRoutes = require("./routes/comments"),
campgroundRoutes = require("./routes/campgrounds"),
indexRoutes = require("./routes/index")
mongoose.connect("mongodb://localhost/yelp_camp_", {
useNewUrlParser: true,
useUnifiedTopology: true,
})
app.use(bodyParser.urlencoded({extended: true}));
app.set("view engine", "ejs");
app.use(express.static(__dirname + "/public"));
app.use(methodOverride("_method"));
app.use(flash());
//seedDB(); //seed the database
//PASSPORT CONFIGURATION
app.use(require("express-session")({
secret: "Bodybuilding is fun",
resave: false,
saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());
passport.use(new LocalStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
app.use(function(req, res, next){
res.locals.currentUser = req.user;
res.locals.error = req.flash("error")
res.locals.success = req.flash("success")
next();
});
app.use("/", indexRoutes);
app.use("/campgrounds", campgroundRoutes);
app.use("/campgrounds/:id/comments", commentRoutes);
app.listen(3000, function (){
console.log('The YelpCamp Server Has Started');
});
Campgrounds.js
var express = require("express");
var router = express.Router();
var Campground = require("../models/campground");
var middleware = require("../middleware");
//INDEX - show all campgrounds
router.get("/", function(req, res){
// Get all campgrounds from DB
Campground.find({}, function(err, allCampgrounds){
if(err){
console.log(err);
} else {
res.render("campgrounds/index",{campgrounds:allCampgrounds});
}
});
});
//CREATE - add new campground to DB
router.post("/", middleware.isLoggedIn, function(req, res){
// get data from form and add to campgrounds array
var name = req.body.name;
var price = req.body.price;
var image = req.body.image;
var desc = req.body.description;
var author = {
id: req.user._id,
username: req.user.username
}
var newCampground = {name: name, price: price, image: image, description: desc, author:author}
// Create a new campground and save to DB
Campground.create(newCampground, function(err, newlyCreated){
if(err){
console.log(err);
} else {
//redirect back to campgrounds page
console.log(newlyCreated);
res.redirect("/campgrounds");
}
});
});
//NEW - show form to create new campground
router.get("/new", middleware.isLoggedIn, function(req, res){
res.render("campgrounds/new");
});
// SHOW - shows more info about one campground
router.get("/:id", function(req, res){
//find the campground with provided ID
Campground.findById(req.params.id).populate("comments").exec(function(err, foundCampground){
if(err || !foundCampground){
req.flash("error", "Campground not found");
res.redirect("back");
} else {
console.log(foundCampground);
//render show template with that campground
res.render("campgrounds/show", {campground: foundCampground});
}
});
});
//EDIT CAMPGROUND ROUTE
router.get("/:id/edit", middleware.checkCampgroundOwnership, function(req, res){
Campground.findById(req.params.id, function(err, foundCampground){
res.render("campgrounds/edit", {campground: foundCampground});
});
});
//UPDATE CAMPGROUND ROUTE
router.put("/:id", middleware.checkCampgroundOwnership, function(req, res){
//find and update the correct campground
Campground.findByIdAndUpdate(req.params.id, req.body.campground, function(err, updatedCampground){
if(err){
res.redirect("/campgrounds");
} else {
res.redirect("/campgrounds/" + req.params.id);
}
});
//redirect somewhere(show page)
});
//DESTROY CAMPGROUND ROUTE
router.delete("/:id", middleware.checkCampgroundOwnership, function(req, res){
Campground.findByIdAndRemove(req.params.id, function(err){
if(err){
res.redirect("/campgrounds");
} else
res.redirect("/campgrounds");
});
});
//middleware
function isLoggedIn(req, res, next){
if(req.isAuthenticated()){
return next();
}
res.redirect("/login");
}
module.exports = router;
I am a begginer at node.js and trying to build a basic todo list but keep getting the error:
Cannot read property 'collection' of undefined.
Can someone please explain what im doing wrong and how to I can get my get post requests working?
Thanks for the help !
routes/index.js
var express = require('express');
var router = express.Router();
var ObjectId = require('mongodb').ObjectId
// Get Homepage
router.get('/', ensureAuthenticated, function(req, res){
req.db.collection('Todo').find().sort({"_id": -1}).toArray(function(err, result) {
//if (err) return console.log(err)
if (err) {
req.flash('error', err)
res.render('index', {
title: 'User List',
data: ''
})
} else {
// render to views/user/list.ejs template file
res.render('index', {
title: 'User List',
data: 'ldld'
})
}
})
})
function ensureAuthenticated(req, res, next){
if(req.isAuthenticated()){
return next();
} else {
//req.flash('error_msg','You are not logged in');
res.redirect('/users/login');
}
}
module.exports = router;
routes/Todo.js
// list dependencies
var express = require('express');
var router = express.Router();
// add db & model dependencies
var mongoose = require('mongoose');
var Todo = require('../models/Todo');
// interpret GET /products - show product listing */
// GET intepret GET /products/edit/:id - show single product edit form */
router.get('/Todo/edit/:id', function (req, res, next) {
//store the id from the url in a variable
var id = req.params.id;
var user_id = req.cookies ?
req.cookies.user_id : undefined;
//use the product model to look up the product with this id
Todo.findById(id,user_id, function (err, product) {
if (err) {
res.send('Product ' + id + ' not found');
}
else {
res.render('edit', { Todo: Todo });
}
});
});
// POST /products/edit/:id - update selected product */
router.post('/Todo/edit/:id', function (req, res, next) {
var id = req.body.id;
var Todo = {
_id: req.body.id,
content: req.body.content,
todos : todos,
updated_at : Date.now()
};
Todo.update({ _id: id}, content, function(err) {
if (err) {
res.send('Product ' + req.body.id + ' not updated. Error: ' + err);
}
else {
res.statusCode = 302;
res.setHeader('Location', 'http://' + req.headers['host'] + '/Todo');
res.end();
}
});
});
// GET /products/add - show product input form
router.get('/Todo/create', function (req, res, next) {
res.render('add');
});
// POST /products/add - save new product
router.post('/Todo/create', function (req, res, next) {
// use the Product model to insert a new product
Todo.create({
content: req.body.content,
user_id:req.cookies.user_id,
updated_at : Date.now()
}, function (err,Todo) {
if (err) {
console.log(err);
res.render('error', { error: err }) ;
}
else {
console.log('Product saved ' + Todo);
res.render('added', {Todo: Todo.content });
}
});
});
// API GET products request handler
router.get('/api/Todo', function (req, res, next) {
Todo.find(function (err, products) {
if (err) {
res.send(err);
}
else {
res.send(Todo);
}
});
});
/* GET product delete request - : indicates id is a variable */
router.get('/Todo/delete/:id', function (req, res, next) {
//store the id from the url into a variable
var id = req.params.id;
//use our product model to delete
Todo.remove({ _id: id }, function (err,Todo) {
if (err) {
res.send('Product ' + id + ' not found');
}
else {
res.statusCode = 302;
res.setHeader('Location', 'http://' + req.headers['host'] + '/Todo');
res.end();
}
});
});
// make controller public
module.exports = router;
views/index.handelbars
<h2 class="page-header">Dashboard</h2>
<p> Hello {{user.name}}
<p>Welcome to your dashboard</p>
<% layout( 'layout' ) -%>
<h1 id="page-title">{{ title }}</h1>
<div id="list">
<form action="/create" method="post" accept-charset="utf-8">
<div class="item-new">
<input class="input" type="text" name="content" />
</div>
</form>
{{#each todo}}
<div class="item">
<a class="update-link" href="/edit/{{#todo._id }}" title="Update this todo item">{{todo.content}}</a>
<a class="del-btn" href="/destroy/{{ #todo._id }}>" title="Delete this todo item">Delete</a>
</div>
{{/each }}
app.js
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var exphbs = require('express-handlebars');
var expressValidator = require('express-validator');
var flash = require('connect-flash');
var session = require('express-session');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var mongo = require('mongodb');
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/loginapp');
var db = mongoose.connection;
var routes = require('./routes/index');
var users = require('./routes/users');
var Todo = require('./routes/Todo');
// Init App
var app = express();
// View Engine
app.set('views', path.join(__dirname, 'views'));
app.engine('handlebars', exphbs({defaultLayout:'layout'}));
app.set('view engine', 'handlebars');
// BodyParser Middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
// Set Static Folder
app.use(express.static(path.join(__dirname, 'public')));
// Express Session
app.use(session({
secret: 'secret',
saveUninitialized: true,
resave: true
}));
// Passport init
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
};
}
}));
// Connect Flash
app.use(flash());
// Global Vars
app.use(function (req, res, next) {
res.locals.success_msg = req.flash('success_msg');
res.locals.error_msg = req.flash('error_msg');
res.locals.error = req.flash('error');
res.locals.user = req.user || null;
next();
});
app.use('/', routes);
app.use('/users', users);
app.use('/Todo', Todo);
// Set Port
app.set('port', (process.env.PORT || 3000));
app.listen(app.get('port'), function(){
console.log('Server started on port '+app.get('port'));
});
Add the following to your app.js, right after var app = express();
app.use(function (req, res, next) {
req.db = db;
next();
});
This will create a reference to your mongoose connection in all the incoming requests, accessible via req.db.
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
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();
});