passport-local-mongoose: No response - node.js

When authenticating with the server, the server does not respond to the POST request. The server recieves the requesst and parses the JSON correctly, but it never sends the response. I have followed many guides and updated Node to no avail.
The code is fairly straightforward, the relevant parts are:
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 mongoose = require('mongoose');
var connectMongo = require('connect-mongo');
var debug = require('debug')('sess:app');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var index = require('./routes/index');
var home = require('./routes/home');
var about = require('./routes/about');
var catalog = require('./routes/catalog');
var branches = require('./routes/branches');
var users = require('./routes/users');
var dbconnect = require('./dbconnect');
var app = express();
var MongoStore = connectMongo(session);
var sessionConnect = dbconnect.Session;
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(cookieParser());
app.use(session({
name: '...',
secret: '...',
resave: false,
saveUninitialized: false,
rolling: true,
store: new MongoStore({ mongooseConnection: sessionConnect }),
cookie: { maxAge: 900000, httpOnly: true, sameSite: true }
}));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(passport.initialize());
app.use(passport.session());
app.use(express.static(path.join(__dirname, 'public')));
// passport setup
var User = require('./models/user')(dbconnect.Models);
passport.use(new LocalStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
// Create user for testing
User.create({username:'admin',password:'12345',deleted:false,kind:'manager'});
// login
// This was attempted with additional redirection options as well
app.post('/login', passport.authenticate('local'), function(req, res) {
// This message never appears in the log
console.log('auth');
res.status(200).end();
});
// logout
app.get('/logout', function(req, res){
req.logout();
res.redirect('/');
});
// 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) {
console.log(err);
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
dbconnect.js:
var mongo = require("mongoose");
mongo.Promise = global.Promise;
var debug = require('debug')('sess:app');
function dbconnect(path){
var userConnStr = 'mongodb://localhost:27017/ise_' + path + '_v6';
var db = mongo.createConnection()
db.on('connecting', function() { debug('Connecting to MongoDB: '); });
db.on('connected', function() { debug('Connected to MongoDB: '); });
db.on('disconnecting', function() { debug('Disconnecting to MongoDB: '); });
db.on('disconnected', function() { debug('Disconnected to MongoDB: '); });
db.on('reconnected', function() { debug('Reconnected to MongoDB: '); });
db.on('error', function(err) { debug('Error to MongoDB: ' + err); });
db.on('open', function() { debug('MongoDB open : '); });
db.on('close', function() { debug('MongoDB close: '); });
process.on('SIGINT', function() { db.close(function () { process.exit(0); });});
db.openUri(userConnStr);
console.log('Pending DB connection');
return db;
};
module.exports = {Session: dbconnect('session'), Models: dbconnect('models'), Custom: dbconnect};
models/user.js:
var mongo = require("mongoose");
var Schema = mongo.Schema;
var passportLocalMongoose = require('passport-local-mongoose');
var userSchema = new Schema({ // create a schema
name: { first: String, last: String }, // field-object (with sub-fields)
kind: { type: String, required: true, enum: ["manager", "employee", "customer", "supplier"] },
email: String,
branch: Number,
created_at: Date,
updated_at: Date,
deleted: { type: Boolean, required: true }
});
userSchema.plugin(passportLocalMongoose);
userSchema.methods.remove = function() {
deleted = true;
save();
};
// on every save, add the date
userSchema.pre('save', function(next) { //callback
// get the current date
var currentDate = new Date();
// change the updated_at field to current date
this.updated_at = currentDate;
// if created_at doesn't exist, add to that field
if (!this.created_at)
this.created_at = currentDate;
next();
});
module.exports = function(db){
return db.model('User', userSchema);
};
The client code uses AngularJS v1:
Controller function:
$scope.signin = function(){
$http.post("login", {'username': $scope.username, 'password': $scope.password}).then(function(data){
// ......
}, function(data){
alert("Wrong username or password");
});
};
HTML Bootstrap modal:
<div id="signInModal" class="modal fade" role="dialog" >
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Sign in</h4>
</div>
<form>
<div class="modal-body">
<div class="form-group">
<input ng-model="username" type="text" placeholder="Username" class="form-control">
</div>
<div class="form-group">
<input ng-model="password" type="password" placeholder="Password" class="form-control">
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-success" ng-click="signin()">Sign in</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</form>
</div>
</div>
</div>

Related

TypeError Cannot set property 'firstName' of null

I know there are similar questions posted, but I haven't been able to find a solution for my problem.
I am trying to create a user profile page where the user can change their information through a form that uses a POST request. However, when the value is entered in the input field, it returns null. I don't have this problem when reading the input data for authenticating a user.
Also, the user is found but req.body returns an empty object.
Tools used:
Node.js v10.16.3
Express v4.17.1
ejs v2.7.1
Express session v1.16.2
Passport v^0.4.0
cookie-parser 1.4.4
body-parser v1.19.0
The user that is found:
{ _id: 5daf5ef80fb0d909e099d211,
username: 'assa',
email: 'easy#gmail.com',
password:
'$2b$05$A81bqD56TDmNoWhiHJVwR.2L7iqZBrRwYu1FEe/bp0TlkTMEUREvS',
firstName: 'test',
__v: 0 }
app.js:
let express = require("express"),
app = express(),
bodyParser = require("body-parser"),
cookieParser = require('cookie-parser'),
session = require("express-session"),
mongoose = require("mongoose"),
passport = require("passport"),
flash = require('connect-flash'),
validator = require('express-validator'),
LocalStrategy = require("passport-local"),
MongoStore = require('connect-mongo')(session);
let indexRoutes = require('./routes/index');
let userRoutes = require('./routes/user');
let User = require("./models/user");
// APP CONFIGURATION
mongoose.connect("mongodb://localhost:27017/test", { useNewUrlParser: true, useUnifiedTopology: true, }).then(() => {
console.log("Connected to MongoDB");
}).catch((error) => {
console.log("Something is wrong...");
});
require('./config/passport');
// View engine setup
app.set("view engine", "ejs");
app.use(express.static(__dirname + "/public"));
// Initial setup
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(validator());
// Session setup
app.use(cookieParser());
app.use(session({
secret: 'somesecretforbytox',
resave: false,
saveUninitialized: false
}));
app.use(flash());
// Initialize passport
app.use(passport.initialize());
app.use(passport.session());
app.use(function (req, res, next) {
res.locals.currentUser = req.user;
res.locals.session = req.session;
next();
});
// ======================
// Connect to route files
// ======================
app.use('/user', userRoutes);
app.use(indexRoutes);
app.listen(3033, function () {
console.log("Listening at port 3033...");
});
user.js
let express = require('express'),
router = express.Router(),
passport = require('passport');
let User = require("../models/user");
// user profile
router.get("/profile", isLoggedIn, function (req, res) {
res.render("user/profile", { currentUser: req.user });
});
router.post('/profile', (req, res) => {
updateRecord(req, res);
res.redirect('/user/profile');
});
function updateRecord(req, res) {
User.findOne({ 'id': req.user.id }, function (err, user) {
let firstName = req.body.firstName;
user.firstName = firstName;
user.save(function (err, doc) {
if (err) {
return done(err);
}
return done(null, doc);
});
});
}
router.get("/profile/edit", isLoggedIn, function (req, res) {
res.render("user/edit", { currentUser: req.user });
});
// ...sign in and signup routes
module.exports = router;
// middleware
function isLoggedIn(req, res, next) {
if (req.isAuthenticated()) {
return next();
}
res.redirect('/user/login');
}
profile.ejs:
<form action="/user/profile" method="POST" class="form-validate form-horizontal">
<fieldset>
<legend>Edit addresss</legend>
<!-- email -->
<div class="control-group">
<div class="control-label">
<label id="jform_email1-lbl" for="jform_email" class="hasPopover required" title="" data-content="Въведете имейл адрес." data-original-title="Email Address">
Email<span class="star"> *</span></label>
</div>
<div class="controls">
<input type="email" name="email" class="validate-email required" id="jform_email" value="<%= (typeof currentUser.email != 'undefined' ? currentUser.email : '') %>" size="30" autocomplete="email" required aria-required="true">
</div>
</div>
<!-- name -->
<div class="control-group">
<div class="control-label">
<label id="jform_fname-lbl" for="jform_fname" class="hasPopover required" title="" data-content="Въведете име." data-original-title="Name">
Name<span class="star"> *</span></label>
</div>
<div class="controls">
<input type="text" name="firstName" id="jform_fname" value="<%= (typeof currentUser.firstName != 'undefined' ? currentUser.firstName : '') %>" class="required" size="30" required aria-required="true">
</div>
</div>
</fieldset>
<div class="form-actions">
<!-- <input type="hidden" name="_csrf" value=" csrfToken "> -->
<button type="submit" class="btn btn-primary validate">
<span>Save</span>
</button>
<!-- <input type="hidden" name="_csrf" value=" csrfToken "> -->
<a class="btn" href="/" title="Cancel">Cancel</a>
</div>
</form>
user schema:
let mongoose = require('mongoose');
let Schema = mongoose.Schema;
let bcrypt = require('bcrypt');
let userSchema = new Schema({
username: { type: String, required: true },
email: { type: String, required: true },
password: { type: String, required: true },
firstName: { type: String },
lastName: { type: String },
address: { type: String },
zip: { type: String },
country: { type: String },
phone: { type: String }
});
userSchema.methods.encryptPassword = function (password) {
return bcrypt.hashSync(password, bcrypt.genSaltSync(5), null);
};
userSchema.methods.validPassword = function (password) {
return bcrypt.compareSync(password, this.password);
}
module.exports = mongoose.model('user', userSchema);
Changing the query to User.findOne({ '_id': req.user.id } as suggested by Subburaj and Matheus Hatje solved the issue.
Snapshot:
router.post('/profile', (req, res) => {
ModelName.create(req.body).then(result => {
if(result){
res.redirect('/user/profile');
}).catch(err){
res.send(err)
}
});
create function write separately, don't compare with update functions.

How to fix MongoDB documents being just id and __v

When I try to add a post to the database the JSON Body is perfectly fine, but when I retrieve these it only shows id and __v (versionKey)
I've tried using body-parser in different ways, such as...
app.use('bodyParser.json()')
var urlencodedParser = bodyParser.urlencoded({ extended: false })
var jsonParser = bodyParser.json();
The last two included in the app.post method.
This is my index.js
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const mongoose = require('mongoose');
const app = express();
const port = 4000;
const postRoutes = express.Router();
let Post = require('./post.model');
var urlencodedParser = bodyParser.urlencoded({ extended: false })
var jsonParser = bodyParser.json();
app.use(cors());
app.use('/', express.static('public'));
app.use(bodyParser.json());
app.use('/posts', postRoutes);
mongoose.connect("mongodb://127.0.0.1:27017/mern-blog-test", { useNewUrlParser: true });
const connection = mongoose.connection;
connection.once('open', function() {
console.log('Succesfully established connection to MongoDB Database');
})
postRoutes.route('/').get(function (req, res) {
Post.find(function (err, posts) {
if (err) {
console.log(err);
} else {
res.json(posts);
}
});
});
postRoutes.route(':id').get(function(req,res) {
let id = req.params.id;
Post.findById(id, function(err, post) {
res.json(post);
});
});
// todoRoutes.route('/add').post(function (req, res) {
// let todo = new Todo(req.body);
// todo.save()
// .then(todo => {
// res.status(200).json({ 'todo': 'todo added successfully' });
// })
// .catch(err => {
// res.status(400).send('adding new todo failed');
// });
// });
app.get('/create', function(req,res){
res.sendFile(__dirname + '/public/add.html');
})
app.post('/makepost', urlencodedParser, function(req,res) {
console.log(req.body);
let post = new Post(req.body);
post.save()
.then(todo => {
res.sendFile(__dirname + '/public/add.html')
})
.catch(err => {
res.status(400).send('adding new post failed!');
});
});
This is my form
<label for="title">Title</label>
<input type="text" name="title">
<label for="category">Category</label>
<select name="category">
<option>Coding</option>
<option>Music</option>
<option>Books</option>
<option>Other Stuff</option>
</select>
<label for="content">Content</label>
<input type="text" name="content">
<input type="submit">
</form>
And my post.model.js
const Schema = mongoose.Schema;
let Post = new Schema({
post_title: {
type: String
},
post_date: {
type: Date
},
post_shortdesc: {
type: String
},
post_content: {
type: String
}
});
module.exports = mongoose.model('Post', Post);
I expect the output to be...
[{"_id":"5d76a7e78b55cd3309b91ecf", "title": "blah", category: "blah", "content": "blah", "__v":0}]
But it is...
[{"_id":"5d76a7e78b55cd3309b91ecf","__v":0}]
Sorry figured it out myself. Form was outputting fields that weren't in the model. Changed form to...
<form id="add-form" method="POST" action="/makepost">
<label for="post_title">Title</label>
<input type="text" name="post_title">
<!-- <label for="post_category">Category</label>
<select name="post_category">
<option>Coding</option>
<option>Music</option>
<option>Books</option>
<option>Other Stuff</option>
</select> -->
<label for="post_date">Content</label>
<input type="date" name="post_date">
<label for="post_content">Content</label>
<input type="text" name="post_content">
<input type="submit">
</form>
Basically just changed the names of input fields to match the model.

Why Passport.js code always redirects to failure?

I am trying to implement passport.js using localstrategy but unable to redirect to success route. Whenever I click on submit button it always redirect me to failure route. Why this is happening and what should I need to do?
Form code:
<form action="/login" method="post">
<div>
<label>Username:</label>
<input type="text" name="username"/>
</div>
<div>
<label>Password:</label>
<input type="password" name="password"/>
</div>
<div>
<input type="submit" value="Log In"/>
</div>
</form>
app.js file code:
var express = require('express');
var app = express();
var connection = require('express-myconnection');
var mysql = require('mysql');
var customers = require('./routes/routes');
var bodyParser = require('body-parser');
var passport = require('passport')
var flash = require('connect-flash')
var LocalStrategy = require('passport-local').Strategy;
var urlencodedParser = bodyParser.urlencoded({
extended: false
})
app.set('view engine', 'ejs');
app.use(
connection(mysql, {
host: 'localhost',
user: 'root',
password: '',
database: 'nodejs'
}, 'request')
);
app.get('/', customers.form);
passport.use('local', new LocalStrategy(
function(username, done) {
console.log('abc');
customers.checkStatus(username, function (err, user) {
if (err) throw err;
if (!user) {
return done(null, false, {message: 'Unknown User'});
}
});
}));
app.post('/login',
passport.authenticate('local', { successRedirect: '/success',
failureRedirect: '/' }),
function (req,res) {
console.log('tets');
res.redirect('/');
}
);
var server = app.listen(8080, function() {
var host = server.address().address;
var port = server.address().port;
console.log("Example app listening at http://%s:%s", host, port);
});
route.js file code:
exports.form = function(req,res){
res.render('form', {
page_title: "Login Form"
});
};
exports.success = function (req, res) {
res.send('wow');
};
exports.checkStatus = function (req, res, username) {
req.getConnection(function(err, connection) {
connection.query('select * from login where username = ?',
[username], function(err, rows) {
});
});
}
As I am able to solve to your problem that not to redirect to failure and after login it is entering into passport function and printing whatever you placed in console.But after entering the details in login form it is redirecting to database connection.There I am getting TypeError: req.getConnection is not a function Which I tried to solve it.Even though I am not able to solve this issue.As I don't have much idea about connecting mysql to nodejs.I am working on mongodb.Here I am giving a link with this try to solve this issue req.getConnection is not a function in express-myconnection
And Replace the app.js code with this I made some changes
var express = require('express');
var path = require('path');
var ejs = require('ejs');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var session = require('express-session');
var customers = require('./routes/routes');
var bodyParser = require('body-parser');
var passport = require('passport')
var flash = require('connect-flash')
var LocalStrategy = require('passport-local').Strategy;
var urlencodedParser = bodyParser.urlencoded({
extended: false
})
var app = express();
var mysql = require('mysql'),
connection = require('express-myconnection');
app.use(
connection(mysql, {
host: 'localhost',
user: 'root',
password: '',
database: 'nodejs'
}, 'request')
);
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(session({secret: '{secret}', name: 'session_id', saveUninitialized: true, resave: true}));
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
app.set('view engine', 'ejs');
passport.use('local', new LocalStrategy(
function(username, done) {
console.log('abc');
customers.checkStatus(username, function (err, user) {
if (err) throw err;
else{
if (!user) {
return done(null, false, {message: 'Unknown User'});
}
if(user){
res.send("User");
}
}
});
}));
app.get('/login', customers.form);
app.get('/success',customers.success);
app.get('/fail',customers.fail)
app.post('/login', passport.authenticate('local', { successRedirect: '/success',
failureRedirect: '/fail',
failureFlash: true
}));
var server = app.listen(8080, function() {
var port = server.address().port;
console.log("Example app listening at http://localhost:%s", port);
});
And here is routes.js code
exports.checkStatus = function (req, res, next) {
req.getConnection(function(err, connection) {
if (err) return next(err);
connection.query('SELECT * FROM login', function(err, rows) {
if (err) console.log("Error Selecting : %s ", err);
res.render('form', {
page_title: "Login form", data: rows
});
});
});
};
exports.form = function(req,res){
res.render('/give the path of form.ejs', { message: req.flash('loginMessage')
});
}
exports.success = function (req, res) {
res.send('wow');
};
exports.fail= function (req, res) {
res.send('Noooooo');
};
open the browser and try with this http://localhost:8080/login.Hope this helps for you...

SMS reminder app, Node/Twilio/Cron/Mongo: TypeError: Cannot read property 'utc' of undefined

I'm working off of some code in a Twilio tutorial, and everything seems to be working fine, except I'm not receiving any notifications. I get this error back after the Notifications Worker runs:
[grunt-develop] > (node:58755) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): TypeError: Cannot read property 'utc' of undefined
Here is the appointment.js file that appears to be causing the error under AppointmentSchema.methods:
var mongoose = require('mongoose');
var moment = require('moment');
var twilio = require('twilio');
var AppointmentSchema = new mongoose.Schema({
phoneNumber: String,
notification : String,
timeZone: String,
time : {type : Date, index : true}
});
AppointmentSchema.methods.requiresNotification = function (date) {
return Math.round(moment.duration(moment(this.time).tz(this.timeZone).utc()
.diff(moment(date).utc())
).asMinutes()) === this.notification;
};
AppointmentSchema.statics.sendNotifications = function(callback) {
// now
var searchDate = new Date();
Appointment
.find()
.then(function (appointments) {
appointments = appointments.filter(function(appointment) {
return appointment.requiresNotification(searchDate);
});
if (appointments.length > 0) {
sendNotifications(appointments);
}
});
// Send messages to all appoinment owners via Twilio
function sendNotifications(docs) {
var client = new twilio.RestClient(ACCOUNTSID, AUTHTOKEN);
docs.forEach(function(appointment) {
// Create options to send the message
var options = {
to: "+1" + appointment.phoneNumber,
from: '+17755834363',
body: "Just a reminder that you have an appointment coming up " + moment(appointment.time).calendar() +"."
};
// Send the message!
client.sendMessage(options, function(err, response) {
if (err) {
// Just log it for now
console.error(err);
} else {
// Log the last few digits of a phone number
var masked = appointment.phoneNumber.substr(0,
appointment.phoneNumber.length - 5);
masked += '*****';
console.log('Message sent to ' + masked);
}
});
});
// Don't wait on success/failure, just indicate all messages have been
// queued for delivery
if (callback) {
callback.call(this);
}
}
};
var Appointment = mongoose.model('appointment', AppointmentSchema);
module.exports = Appointment;
I have no idea why it's undefined, everything appears to be showing up fine in the db. And I don't know if this is what is causing the notifications to not actually be sent. I've been laboring over this for some time, if anyone has any insight that would be great.
File structure:
root
├ config
| ├ auth.js
| ├ database.js
| ├ passport.js
├ controllers
| ├appointments.js
| ├routes.js
├ models
├appointment.js
├users.js
├ public
├ workers
├notificationsWorker
├ app.js
├ scheduler.js
Other relevant files to notifications:
appointments.js
var momentTimeZone = require('moment-timezone');
var Appointment = require('../models/appointment');
var moment = require('moment');
module.exports = function(app, client) {
app.post('/user', function(req, res, next) {
var phoneNumber = req.body.phoneNumber;
var notification = req.body.notification;
var timeZone = req.body.timeZone;
var time = moment(req.body.time, "MM-DD-YYYY hh:mma");
var appointment = new Appointment({
phoneNumber: phoneNumber,
notification: notification,
timeZone: timeZone,
time: time
});
appointment.save()
.then(function () {
res.redirect('/user');
});
});
notificationsWorker.js
var Appointment = require('../models/appointment')
var notificationWorkerFactory = function(){
return {
run: function(){
Appointment.sendNotifications();
}
};
};
module.exports = notificationWorkerFactory();
scheduler.js
var CronJob = require('cron').CronJob;
var notificationsWorker = require('./workers/notificationsWorker');
var moment = require('moment');
var schedulerFactory = function(){
return {
start: function(){
new CronJob('00 * * * * *', function() {
console.log('Running Send Notifications Worker for ' + moment().format());
notificationsWorker.run();
}, null, true, '');
}
};
};
module.exports = schedulerFactory();
And finally the app.js file:
const dotenv = require('dotenv').config({path: '.env'});
const exp = require('express');
const bodyParser = require('body-parser'); //body parser
const methodOverride = require('method-override'); //method override
const app = exp();
const session = require('express-session');
const PORT = process.env.PORT || 3000;
const fetchUrl = require('fetch').fetchUrl;
const request = require('request');
const sass = require('node-sass');
const exphbs = require('express-handlebars');
const favicon = require('serve-favicon');
const morgan = require('morgan');
const fs = require('fs');
const path = require('path');
const cookieParser = require('cookie-parser');
const mongoose = require('mongoose');
var appointments = require('./controllers/appointments');
var scheduler = require('./scheduler');
var ACCOUNTSID = process.env.TWILIO_ACCOUNT_ID;
var AUTHTOKEN = process.env.TWILIO_AUTH_TOKEN;
var twilio = require('twilio');
var client = new twilio.RestClient(ACCOUNTSID, AUTHTOKEN);
//databse stuff
const db = require('./config/database.js');
// mongoose.connect(db.url); // connect to our database
//passport
const passport = require('passport');
const flash = require('connect-flash');
app.use(session({ secret: 'blahblahblahbleck' })); // session secret
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash()); // use connect-flash for flash messages stored in session
//views/middleware configs
app.engine('handlebars', exphbs({
layoutsDir: __dirname + '/views/layouts/',
defaultLayout: 'main',
partialsDir: [__dirname + '/views/partials/']
}));
app.set('view engine', 'handlebars');
app.set('views', __dirname + '/views');
app.locals.pretty = true
app.use('/', exp.static(__dirname + '/public'));
app.use('/bower_components', exp.static(__dirname + '/bower_components'));
app.use(methodOverride('_method')) //method override
app.use(bodyParser.urlencoded({
extended: false
// app.use(favicon(__dirname + '/public/imgages/favicon.ico'));
})); //body parser
app.use(bodyParser.json()); //body parser
app.use(cookieParser());
app.use(morgan('dev'));
app.locals.moment = require('moment');
require('./config/passport')(passport);
require('./controllers/routes')(app, passport);
require('./controllers/appointments')(app, client, db);
app.use('./controllers/appointments', appointments);
app.use('/', appointments);
// dynamically set controllers(routes)
fs.readdirSync('./controllers').forEach(function(file) {
routes = require('./controllers/' + file);
});
//start the server
app.listen(PORT, function() {
console.log('things that make you go hmmm on port ' + PORT);
});
scheduler.start();
module.exports = app;
==================UPDATED=================
My form input view:
<form class="omb_loginForm" action="/" autocomplete="off" method="POST">
<span class="help-block"></span>
<div class="input-group">
<span class="input-group-addon"></span>
<input type="text" class="form-control" name="phoneNumber" placeholder="phone number">
</div>
<span class="help-block"></span>
<div class="input-group">
<span class="input-group-addon"></span>
<input type="text" class="form-control" name="notification" placeholder="notification">
</div>
<span class="help-block"></span>
<div class="input-group">
<span class="input-group-addon"></span>
<select class="form-control" name="timeZone">
{{#each timeZone}}
<option>{{this}}</option>
{{/each}}
</select>
</div>
<span class="help-block"></span>
<div class="input-group date" id="datetimepicker1">
<input class="form-control" name="time">
<span class="input-group-addon glyphicon-calendar glyphicon">
</span>
</div>
<span class="help-block"></span>
<button class="btn btn-lg btn-primary btn-block" type="submit">
Submit
</button>
</form>
Original form view:
.form-group
label.col-sm-4.control-label(for='inputName') Name *
.col-sm-8
input#inputName.form-control(type='text', name='name', placeholder='Name', required='', data-parsley-maxlength='20', data-parsley-maxlength-message="This field can't have more than 20 characters", value="#{appointment.name}")
.form-group
label.col-sm-4.control-label(for='inputPhoneNumber') Phone Number
.col-sm-8
input#inputPhoneNumber.form-control(type='number', name='phoneNumber', placeholder='Phone Number', required='', value="#{appointment.phoneNumber}")
.form-group
label.col-sm-4.control-label(for='time') Appointment Date
.col-sm-8
input#inputDate.form-control(type='text', name='time', placeholder='Pick a Date', required='', value="#{moment(appointment.time).format('MM-DD-YYYY hh:mma')}")
.form-group
label.col-sm-4.control-label(for='selectNotification') Notification Time
.col-sm-8
select#selectDelta.form-control(name='notification', required='', value="#{appointment.notification}")
option(selected=appointment.notification == '', value='') Select a time
option(selected=appointment.notification == '15', value='15') 15 Minutes
option(selected=appointment.notification == '30', value='30') 30 Minutes
option(selected=appointment.notification == '45', value='45') 45 Minutes
option(selected=appointment.notification == '60', value='60') 60 Minutes
.form-group
label.col-sm-4.control-label(for='selectTimeZone') Time Zone
.col-sm-8
select#selectTimeZone.form-control(name='timeZone', required='', value="#{appointment.timeZone}")
each zone in timeZones
option()
option(selected=zone == appointment.timeZone, value="#{zone}") !{zone}
routes.js
app.get('/user', isLoggedIn, function(req, res) {
res.render('user', {
user : req.user,
timeZone: timeZones(),
appointment : new Appointment({
phoneNumber: "",
notification: '',
timeZone: "",
time:''}),
loggedIn: true, // get the user out of session and pass to template
layout: 'home'
});
});
I was able to finally get it working by changing the logic around in requiresNotification. Here's the updated code:
AppointmentSchema.methods.requiresNotification = function (date) {
var apptDate = moment.utc(this.time);
var current = moment.utc(date);
return Math.round(moment.duration(current.diff(apptDate))
.asMinutes()) === 0;
};
I'm finding the duration of the difference between the appointment time and current time. So now when the difference in minutes of the appointment date/time and the current date/time is 0, the notification is sent.

Database is not creating using express and node.js

I am working on simple registration page using express and mongodb this is my html
<body>
<form>
<div align="center" ng-controller="regiCtrl">
<table>
<tr>
<td>User Name :</td>
<td><input type="text" ng-model="user.userName" />
</td></tr>
<tr>
<td>Password :</td>
<td><input type="password" ng-model="user.password" />
</td></tr>
<tr>
<tr><td>
<input type="button" value = "Submit" ng-click="regi()"></td>
<td>
</td></tr>
</table>
</div>
</form>
</body>
and this is my controller
lyfee.controller('regiCtrl',['$scope','$http', function($scope,$http) {
$scope.user = {};
$scope.regi = function () {
// var data = {User: $scope.user }
console.log($scope.user);
$http.post('/regi',$scope.user);
console.log("post request send");
}
}]);
have a look of my server.js
var express = require('express');
var app = express();
var port = process.env.PORT || 80;
var cookieParser = require('cookie-parser');
var session = require('express-session');
var bodyParser = require('body-parser');
var jwt = require('jsonwebtoken');
//Used for open index.html by default(open html page which one will be in public folder)
app.use(express.static(__dirname + "/public"));
// configure app to use bodyParser()
// this will let us get the data from a POST
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(cookieParser());
app.use(session({secret: 'anystringoftext',
saveUninitialized: true,
resave: true}));
app.use('/', function(req, res){
//res.send('Our First Express program!');
//res.redirect('index.html');
//console.log(req.cookies);
// console.log(req.session);
console.log("HELLO WE ARE IN SERVER");
});
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/lyfee_module');
console.log("Connection created");
var Userschema = require('./models/dbSchema');
app.post('/regi',function(req,res){
console.log("post request get");
/*
var schema = new Userschema();
schema.Firstname = req.body.Firstname;
schema.Lastname = req.body.Lastname;
schema.City = req.body.city;
schema.Email = req.body.email;
schema.Userid = req.body.userid;
schema.Password = req.body.password;
console.log(schema.Firstname);
// console.log(schema.Lastname);
*/
console.log(req);
var schema = new Userschema({
userName : req.body.userName,
password : req.body.password,
});
console.log(req.body);
console.log(schema);
schema.save(function(err) {
if (err)
res.send(err);
res.json({ message: 'Record Inserted', userName: req.body.userName, password: req.body.password});
});
});
app.listen(port);
console.log('Server running on port: ' + port);
it's my config.js
module.export = {
'secret' : 'lyfee',
'database': 'mongodb://localhost/lyfee_module'
};
and finally is my db
var mongoose = require('mongoose');
var User = new mongoose.Schema({
userName: String,
password: String,
});
//console.log(User);
module.exports = mongoose.model('user', User);
my entries is not storing in database even database with lyfee_module is not creating please help me, how to i can solve this problem ?
i think every thing is looking fine just add running port of mongodb in config.js like
mongodb://localhost:27017/
Have you tried using a callback with mongoose.connect()? I would recommend trying the following and see if you get any errors:
mongoose.connect(mongoUrl, err => {
console.log(err || `MongoDB connected at ${mongoUrl}`);
})

Resources