Iam trying to create a user profile in my mongo db. I already have a basic user registration /session, login/logout system. However I want to add more fields. For instance how would add a 'last name' or 'date of birth' to the below code?
index.js
var express = require('express');
var passport = require('passport');
var Account = require('../models/account');
var router = express.Router();
router.get('/', function (req, res) {
res.render('index', { user : req.user });
});
router.get('/register', function(req, res) {
res.render('register', { });
});
router.post('/register', function(req, res, next) {
console.log(req.body);
Account.register(new Account({ username : req.body.username, firstname: req.body.firstname }) req.body.password, function(err, account) {
if (err) {
return res.render("register", {info: "Sorry. That username already exists. Try again."});
}
passport.authenticate('local')(req, res, function () {
req.session.save(function (err) {
if (err) {
return next(err);
}
res.redirect('/');
});
});
});
});
router.get('/login', function(req, res) {
res.render('login', { user : req.user });
});
router.post('/login', passport.authenticate('local'), function(req, res, next) {
req.session.save(function (err) {
if (err) {
return next(err);
}
res.redirect('/');
});
});
router.get('/logout', function(req, res, next) {
req.logout();
req.session.save(function (err) {
if (err) {
return next(err);
}
res.redirect('/');
});
});
router.get('/ping', function(req, res){
res.status(200).send("pong!");
});
module.exports = router;
Account.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var passportLocalMongoose = require('passport-local-mongoose');
var Account = new Schema({
username: String,
password: String,
firstname: String
});
Account.plugin(passportLocalMongoose);
module.exports = mongoose.model('Account', Account);
Register.jade
extends layout
block content
.containerhome
h1 Register
.containerhomeborder
br
br
br
br
br
br
br
br
br
br
form(role='form', action="/register",method="post")
.form-group
input.form-control(type='text', name="username", placeholder='Enter Username')
.form-group
input.form-control(type='text', name="firstname", placeholder='First Name')
.form-group
input.form-control(type='password', name="password", placeholder='Password')
button.btn.btn-default(type='submit') Submit
a(href='/')
button.btn.btn-primary(type="button") Cancel
br
h4= info
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 routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
var mongoose = require('mongoose');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy
// dependencies
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 LocalStrategy = require('passport-local').Strategy;
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');
// 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(require('express-session')({
secret: 'keyboard cat',
resave: false,
saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
// passport config
var Account = require('./models/account');
passport.use(new LocalStrategy(Account.authenticate()));
passport.serializeUser(Account.serializeUser());
passport.deserializeUser(Account.deserializeUser());
// mongoose
mongoose.connect('mongodb://localhost/passport_local_mongoose_express4');
// 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;
// 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('/', 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;
User.js
var express = require('express');
var router = express.Router();
/* GET users listing. */
router.get('/', function(req, res, next) {
res.send('respond with a resource');
});
module.exports = router;
In Account.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var passportLocalMongoose = require('passport-local-mongoose');
var Account = new Schema({
username: String,
password: String,
firstname: String,
lastname: String,
dob: Date
});
Account.plugin(passportLocalMongoose);
module.exports = mongoose.model('Account', Account);
And where you are adding the fields to the new model:
// ...
Account.register(new Account({
username :req.body.username,
firstname: req.body.firstname,
lastname: req.body.lastname,
dob: req.body.dob
}) req.body.password, function(err, account) {
// ...
I would highly suggest reading the mongoose documentation: http://mongoosejs.com/docs/schematypes.html
http://mongoosejs.com/docs/models.html
Related
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
);
When I make make post request to my MEAN app I am getting req.body.username as undefined upon debugging.
Below is my route file:
var mongoose = require('mongoose');
var express = require('express');
var passport = require('passport');
var User = mongoose.model('User');
var auth = require('../auth');
var router = express.Router();
router.post('/users', function (req, res, next) {
var user = new User();
user.username = req.body.username;
user.email = req.body.email;
user.setPassword(req.body.password);
user.save(function (err) {
if (err) { return next(err); }
return res.json({ token: user.to() })
});
});
router.post('/users/login', function(req, res, next){
if(!req.body.user.email){
return res.status(422).json({errors: {email: "can't be blank"}});
}
if(!req.body.user.password){
return res.status(422).json({errors: {password: "can't be blank"}});
}
passport.authenticate('local', {session: false}, function(err, user, info){
if(err){ return next(err); }
if(user){
user.token = user.generateJWT();
return res.json({user: user.toAuthJSON()});
} else {
return res.status(422).json(info);
}
})(req, res, next);
});
router.get('/user', auth.required, function(req, res, next){
User.findById(req.payload.id).then(function(user){
if(!user){ return res.sendStatus(401); }
return res.json({user: user.toAuthJSON()});
}).catch(next);
});
router.put('/user', auth.required, function(req, res, next){
User.findById(req.payload.id).then(function(user){
if(!user){ return res.sendStatus(401); }
if(typeof req.body.user.username !== 'undefined'){
user.username = req.body.user.username;
}
if(typeof req.body.user.email !== 'undefined'){
user.email = req.body.user.email;
}
if(typeof req.body.user.bio !== 'undefined'){
user.bio = req.body.user.bio;
}
if(typeof req.body.user.image !== 'undefined'){
user.image = req.body.user.image;
}
if(typeof req.body.user.password !== 'undefined'){
user.setPassword(req.body.user.password);
}
return user.save().then(function(){
return res.json({user: user.toAuthJSON()});
});
}).catch(next);
});
module.exports = router;
And below is my 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 passport = require('passport');
var mongoose = require('mongoose');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// 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: true }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
mongoose.connect('mongodb://localhost/conduit');
require('./models/Users');
require('./routes/index');
require('./routes/auth');
var users=require('./routes/api/users');
require('./routes/api/index');
app.use('/', 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 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;
I have my trying to find a solution but so far have been unfortunately unable to do so. I tried a couple of suggestions like change the order of bodyParser middleware and all but so far have been unable to do so.
Im having trouble connecting Node.js application with sql database.
Error occurs is "req.getConnection is not a function".
I am trying to get data from the database the moment I click on a certain page (eg.users).
My code is as below
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 flash = require('express-flash');
var session = require('express-session');
var expressValidator = require('express-validator');
var methodOverride = require('method-override');
var connection = require('express-myconnection');
var mysql = require('mysql');
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');
// 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(session({secret:"mysecretpass"}));
app.use(flash());
app.use(expressValidator());
app.use(cookieParser());
app.use(require('less-middleware')(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/users', users);
app.use(methodOverride(function(req, res){
if (req.body && typeof req.body === 'object' && '_method' in req.body)
{
var method = req.body._method;
delete req.body._method;
return method;
}
}));
/*-----------------------------------------
* Connection peer, register as middleware
* type koneksi:single,pool and request
-----------------------------------------*/
app.use(
connection(mysql,{
host:'localhost',
user:'root',
password:'',
port:3306,
database:'stores'
},'single')
);
// 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('dashboard', { title: 'Dashboard' });
});
router.get('/admin_users', function(req, res, next) {
req.getConnection(function(err,connection){
var query = connection.query('SELECT * FROM users',function(err,rows)
{
if(err)
var errornya = ("Error Selecting : %s ",err );
req.flash('msg_error', errornya);
res.render('admin_users',{title:"Admin Users",data:rows});
});
//console.log(query.sql);
});
});
module.exports = router;
You are adding the express-myconnection middleware after your routes middleware. Middleware is executed in the order it is added, and as such the getConnection function is not defined on the req object until after your express-myconnection middleware is executed.
Simply move the connection middleware above the usage of routes, ie.
app.use(
connection(mysql,{
host:'localhost',
user:'root',
password:'',
port:3306,
database:'stores'
},'single')
);
app.use('/', routes);
app.use('/users', users);
Hi I have following code in my
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');
// Used to connect to the MongoDB database
var mongo = require('mongodb')
var routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
// Define the directory with the views and to use Jade
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')));
// Define what route files to use being routes/index.js for /
// routes/users.js for /users
// The route files then render the page
app.use('/', routes);
app.use('/users', users);
console.log("The Value of Appadadasd",""+ app);
// 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;
Here is my index.js
var express = require('express');
var router = express.Router();
var mongodb = require('mongodb');
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
var MongoClient = mongodb.MongoClient;
var url = 'mongodb://localhost:27017/AddServer';
// Use connect method to connect to the Server
MongoClient.connect(url, function (err, db) {
if (err) {
console.log('Unable to connect to the mongoDB server. Error:', err);
} else {
//HURRAY!! We are connected. :)
console.log('Connection established to', url);
// Get the documents collection
var collection = db.collection('users');
//Create some users
var user1 = {name: 'modulus admin', age: 42, roles: ['admin', 'moderator', 'user']};
var user2 = {name: 'modulus user', age: 22, roles: ['user']};
var user3 = {name: 'modulus super admin', age: 92, roles: ['super-admin', 'admin', 'moderator', 'user']};
// Insert some users
collection.insert([user1, user2, user3], function (err, result) {
if (err) {
console.log(err);
} else {
console.log('Inserted %d documents into the "users" collection. The documents inserted with "_id" are:', result.length, result);
}
//Close connection
db.close();
});
}
});
module.exports = router;
and my users.js
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/users', function(req, res, next) {
res.render('index', { title: 'Express' });
});
module.exports = router;
When i type http://localhost:3000/ it working for perfectly
but when i am trying to call http://localhost:3000/users its giving me
Not Found
404
Error: Not Found
at D:\AddServer\AddServer\app.js:45:13
at Layer.handle [as handle_request] (D:\AddServer\AddServer\node_modules\express\lib\router\layer.js:95:5)
at trim_prefix (D:\AddServer\AddServer\node_modules\express\lib\router\index.js:312:13)
at D:\AddServer\AddServer\node_modules\express\lib\router\index.js:280:7
at Function.process_params (D:\AddServer\AddServer\node_modules\express\lib\router\index.js:330:12)
at next (D:\AddServer\AddServer\node_modules\express\lib\router\index.js:271:10)
at D:\AddServer\AddServer\node_modules\express\lib\router\index.js:618:15
at next (D:\AddServer\AddServer\node_modules\express\lib\router\index.js:256:14)
at Function.handle (D:\AddServer\AddServer\node_modules\express\lib\router\index.js:176:3)
at router (D:\AddServer\AddServer\node_modules\express\lib\router\index.js:46:12)
Its not routing to users.js I think i am doing some silly mistakes but i am new node not able to figure it out.
You are mounting users routes at /users by defining
app.use('/users', users);
But, in your users.js file, you have defined only /users route, which is accessible by http://localhost:3000/users/users (because of mounting), not by http://localhost:3000/users
Try changing that path of the route from /users to / in users.js
e.g.
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
Edit
After discussing the exact requirement, you can do the following changes to access http://localhost:3000/user
app.js
app.use('/user', users);
users.js
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
I'm starting to learn Node and Express, but I currently can't get some of my routes to work.. Here's the app.js file that I'm currently using
EDIT: Here's my updated files, but I stil get a 404
var db = require('./db');
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 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(session({
secret: 'keyboard cat',
resave: false,
saveUninitialized: false,
}));
app.use(express.static(path.join(__dirname, 'public')));
app.use('/users', users);
app.use('/', routes);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
//res.send(req.path)
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;
And the route I can't view is '/users/userlist' here is my userlist.js route
EDIT: I've moved '/users/userlist' into the users.js route
var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var User = mongoose.model('User');
/* GET users listing. */
router.get('/users/add/*:', function(req, res, next) {
var params = req.params[0].split("/");
if(params.length>=2){
var newUser = new User({username: params[0], password:params[1]});
newUser.save(function(err, fluffy){
if(err)
res.send(err);
});
}
res.send('Account Created!');
});
router.get('/users/userlist', function(req, res) {
var users;
User.find(function(err, _users){
if(err)
users="ERROR";
else
users=_users;
});
res.send(users);
});
module.exports = router;
When I try and point my browser to http://localhost:3000/users/userlist I just get a 404.
You have made a mistake while declaring routes in app.js,remove below code.
app.use('/users/userlist',userlist);