Trying to post from a register form in a MEAN application, I can use Postman to successfully post using x-www-form-urlencoded, but the request body in the app is empty when I console.log it.
The register form (part):
<form class="form-horizontal" ng-submit="register.saveUser()">
<div class="form-group">
<label class="col-sm-2 control-label">Name</label>
<div class="col-sm-6">
<input type="text" class="form-control" ng-model="user.userData.name">
api.js (part)
var bodyParser = require('body-parser'); // get body-parser
var User = require('../models/user');
var jwt = require('jsonwebtoken');
var config = require('../../config');
var superSecret = config.secret;
module.exports = function(app, express) {
var apiRouter = express.Router();
apiRouter.post('/register', function(req, res) {
var user = new User();
user.name = req.body.name;
user.username = req.body.username;
user.password = req.body.password;
console.log(req.body); //EMPTY
I have app.use bodyParser in server.js before the call to api.js
server.js (part)
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var apiRoutes = require('./app/routes/api')(app, express);
app.use('/api', apiRoutes);
I'm doing something wrong but can't see what.
Added for #mscdex:
register.saveUser() refers to userRegisterController saveUser() function:
.controller('userRegisterController', function(User) {
var vm = this;
// function to create a user
vm.saveUser = function() {
vm.processing = true;
vm.message = '';
// use the register function in the userService
User.register(vm.userData)
.success(function(data) {
vm.processing = false;
vm.userData = {};
vm.message = data.message;
});
};
This uses the userService register function:
// register a user
userFactory.register = function(userData) {
return $http.post('/api/register/', userData);
};
This calls api file which I have posted above.
BTW when I use Postman the console.dir(req.headers['content-type']) shows 'application/x-www-form-urlencoded' and is successful.
I spent quite a few hours on this today and ultimately the problem of 'undefined' being received by the apiRouter function was due to my use of
<input type="text" class="form-control" ng-model="user.userData.name">
whereas I should have used
<input type="text" class="form-control" ng-model="register.userData.name">
because I had used
.when('/register', {
templateUrl: 'app/views/pages/register.html',
controller: 'userCreateController',
controllerAs: 'register'
});
in the apiRoutes file.
I'm still learning the usage of ControllerAs in this context.
Related
I am using the following stack :
React
PassportJS
NodeJS
Express and express-session
create-react-app with webpack dev server proxying API requests to my node server as mentioned in this article
When I do a form submit, I get an error Cannot POST however when I submit to the SAME url using POSTMAN or curl XPOST, I get results. Here is my server.js code :
'use strict';
const PORT = process.env.PORT || 3001;
const express = require('express');
const app = express();
const path = require('path');
const passport = require('passport')
const initPassport = require('./passport/init');
const session = require('express-session')
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser')
const configDB = require('./config/database.js');
const MongoStore = require('connect-mongo')(session);
var flash = require('connect-flash');
//Connect to mongo
mongoose.connect(configDB.url, {
useMongoClient: true
}).then(() => console.log('connection with database succeeded'))
.catch(err => console.error(err));
// Initialize Passport
initPassport(passport);
// Serve static assets
app.use(express.static(path.resolve(__dirname, '..', 'build')));
//use cookie parser to store data
app.use(cookieParser());
app.use(session({
secret: 'mysecret',
store : new MongoStore ({
db : mongoose.connection.db,
host : '127.0.0.1',
port : '27017',
url : configDB.url
}),
maxAge : 2 * 60 * 60 * 1000,
resave: false,
saveUninitialized: false
})); // session secret
app.use(bodyParser.urlencoded({ extended: false }));
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash()); // use connect-flash for flash messages stored in session
app.post('/signup', passport.authenticate('signup', {
successRedirect: '/',
failureRedirect: '/signup'
}));
app.listen(PORT, () => {
console.log(`App listening on port ${PORT}!`);
});
Form PAGE :
import React, { Component } from 'react';
import constants from 'constants/AuthPageConstants';
class RegisterForm extends Component {
render() {
return (
<div className="tab-pane fade in" id="basic-tab2">
<form action="/signup" method="POST">
<div className="text-center">
<div className="icon-object border-success text-success"><i className="icon-plus3"></i></div>
<h5 className="content-group">{constants.register_form_title} <small className="display-block">{constants.register_form_subtitle}</small></h5>
</div>
<div className="form-group has-feedback has-feedback-left">
<input type="text" name="username" className="form-control" placeholder={constants.register_username_placeholder} />
<div className="form-control-feedback">
<i className="icon-user-check text-muted"></i>
</div>
</div>
<div className="form-group has-feedback has-feedback-left">
<input type="password" name="password" className="form-control" placeholder={constants.register_password_placeholder} />
<div className="form-control-feedback">
<i className="icon-user-lock text-muted"></i>
</div>
</div>
<div className="form-group has-feedback has-feedback-left">
<input type="text" name="email" className="form-control" placeholder={constants.register_email_placeholder} />
<div className="form-control-feedback">
<i className="icon-mention text-muted"></i>
</div>
</div>
<div className="content-divider text-muted form-group"><span>Additions</span></div>
<div className="form-group">
<div className="checkbox">
<label>
<input type="checkbox" className="styled" />
{constants.tos_txt.substring(0, constants.tos_txt.indexOf(" "))} {constants.tos_txt.substr(constants.tos_txt.indexOf(" ") + 1)}
</label>
</div>
</div>
<button type="submit" className="btn bg-indigo-400 btn-block">Register <i className="icon-circle-right2 position-right"></i></button>
</form>
</div>
)
}
}
export default RegisterForm
Signup passport strategy
var LocalStrategy = require('passport-local').Strategy;
var User = require('../models/user');
var bCrypt = require('bcrypt');
module.exports = function(passport){
passport.use('signup', new LocalStrategy({
passReqToCallback : true // allows us to pass back the entire request to the callback
},
function(req, username, password, done) {
console.log("In Signup");
findOrCreateUser = function(){
// find a user in Mongo with provided username
User.findOne({ 'username' : username }, function(err, user) {
// In case of any error, return using the done method
if (err){
console.log('Error in SignUp: '+err);
return done(err);
}
// already exists
if (user) {
console.log('User already exists with username: '+username);
return done(null, false, req.flash('message','User Already Exists'));
} else {
// if there is no user with that email
// create the user
var newUser = new User();
// set the user's local credentials
newUser.username = username;
newUser.password = createHash(password);
newUser.email = req.param('email');
newUser.firstName = "firstName";
newUser.lastName = "lastName";
// save the user
newUser.save(function(err) {
if (err){
console.log('Error in Saving user: '+err);
throw err;
}
console.log('User Registration succesful');
return done(null, newUser);
});
}
});
};
// Delay the execution of findOrCreateUser and execute the method
// in the next tick of the event loop
process.nextTick(findOrCreateUser);
})
);
// Generates hash using bCrypt
var createHash = function(password){
return bCrypt.hashSync(password, bCrypt.genSaltSync(10));
}
}
UPDATE
The issue appears to be due to the presence of the proxy. The form submit works if I directly call the nodejs backend API which is running on a different port (by allowing CORS) and remove the proxy. If I insert the proxy, and make the form point to the weback dev server, then form submit does not call the my nodeJS API. However, proxying works with curl and POSTMAN. Weird how curl works and form submit doesn't. Any pointers here will be helpful.
try to clear browser cache . if you are using chrome
go to settings
type cache in search
browse to bottom and clear cache .
if it doesnt solve the problem please write back
I'm building a website, and i have a registration form where i need to submit a form via POST, and register a user in a mongoDB databse. The website works fine so far, but when i submit the registration form the browser just "waits for localhost" forever. I use EJS as my templating engine, although i don't think that matters.
register.ejs:
<% include partials/header %>
<%include partials/nav %>
<h1>REGISTER</h1>
Login
<form id="registerForm" action="/register" method="post">
<div class="form-group">
<label for="exampleInputEmail1">Email address</label>
<input type="email" name="username" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter email">
<small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input type="password" name="password" class="form-control" id="exampleInputPassword1" placeholder="Password">
<small id="passwordHelp" class="form-text text-muted">Your password must be at least 8 characters long.</small>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
<% include partials/footer %>
app.js:
var express = require('express'),
app = express(),
mongoose = require('mongoose'),
passport = require("passport"),
bodyParser = require("body-parser"),
User = require("./models/user"),
LocalStrategy = require("passport-local"),
passportLocalMongoose = require("passport-local-mongoose");
//Set up MongoDB
var mongo = require("mongo");
var MongoClient = require('mongodb').MongoClient;
var assert = require('assert');
var ObjectId = require('mongodb').ObjectID;
var url = 'mongodb://localhost:27017/customerapp';
//MongoJS
var mongojs = require("mongojs");
var db = mongojs("customerapp", ["users"]);
//Mongoose
var mongoose = require('mongoose');
mongoose.Promise = global.Promise
mongoose.createConnection("mongodb://localhost:27017/customerapp");
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({extended: true}));
app.use(require("express-session")({
secret: "wah wah wah",
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());
var index = require("./routes/index");
var about = require("./routes/about");
var login = require("./routes/login");
//var register = require("./routes/register");
app.all("index", index);
app.all("about", about);
app.all("login", login);
//app.all("register", register);
// AUTH Routes
//Register get request
app.get("/register", function(req, res) {
res.render("register");
});
//Handle post register req. at '/register'
app.post("/register", function(req, res) {
User.register(new User({
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("/secret")
})
});
});
app.listen(process.env.PORT || 3000, process.env.IP, function () {
console.log('Example app listening on port 3000!')
})
You are using three params instead of two, use it like this.
//Handle post register req. at '/register'
app.post("/register", function(req, res) {
User.register(new User({
username: req.body.username,
password: req.body.password
}),
function(err, user) {
if(err) {
console.log(err);
return res.render("register");
}
passport.authenticate("local")(req, res, function() {
res.redirect("/secret")
})
});
});
Check to make sure your versions of mongoDB and mongoose are compatible. You can find a compatibility chart here.
In addition to checking your MongoDB and mongoose versions, you should also check if it's actually connecting to the database by using a callback function when you connect to the server, like so:
//Connecting to database using mongoose.connect with a callback
mongoose.connect("mongodb://localhost:27017/customerapp", function(error) {
if(error) {
console.log("There was an error connecting to MongoDB.");
console.log(error);
} else {
console.log("Successfully connected to MongoDB!");
}
});
This callback may also work with mongoose.createConnection instead of mongoose.connect, but I haven't tried. If neither message prints to the console, then the app is not getting any response from the server, not even an error.
For some reason, as long as mongoDB is running at all, GET requests still seem to work even if the connection attempt hangs, but POST requests run into trouble.
Source: Mongoose never connects to mongodb
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.
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}`);
})
I'm pretty new in node.js and I'm learning by my own, so I'm sorry if I ask stupid/easy questions.
I want to make a register form and insert the data into mongodb. I'm using express and mongoose to do that but I don't know how to insert the data in my database.
Here is what I've got:
My structure is:
Project
|--models
`--user.js
|--routes
`--api.js
|--www
`--register.html
|--server.js
package.json
The content is:
server.js
var express = require('express');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var path = require('path');
var user = require('./models/user');
mongoose.connect('mongodb://localhost/Testdb');
var app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use('/api', require('./routes/api'));
app.get("/register", function(req, res){
res.sendFile("register.html", { root: path.join(__dirname, './www')});
});
app.post("/register", function(req, res){
var u = new user();
u.firstname = req.body.firstname;
u.lastname = req.body.lastname;
u.locality = req.body.locality;
u.email = req.body.email;
u.password = req.body.password;
//here I get the parameters correctly but I don't now what to do with the user object to insert it in the database
});
app.listen(3000);
console.log('API is running on port 3000');
user.js
var restful = require('node-restful');
var mongoose = restful.mongoose;
var crypto = require('crypto');
var userSchema = new mongoose.Schema({
firstname: String,
lastname: String,
locality: String,
email: {type: String, unique: true},
password: String
});
userSchema.pre('save', function(next) {
var user = this;
var shasum = crypto.createHash('sha1');
shasum.update(user.password);
user.password = shasum.digest('hex');
next();
});
module.exports = restful.model('Users', userSchema);
api.js
var express = require('express');
var router = express.Router();
var user = require('../models/user');
user.methods(['get', 'put', 'post', 'delete']);
user.register(router, '/users');
module.exports = router;
register.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title><Document></Document></title>
</head>
<body>
<form action="/register" method="POST">
<label>Name</label><br/>
<input type="text" name="firstname"/><br/>
<label>Surname</label><br/>
<input type="text" name="lastname"/><br/>
<label>Locality</label><br/>
<input type="text" name="locality"/><br/>
<label>Email</label><br/>
<input type="text" name="email"/><br/>
<label>Password</label><br/>
<input type="password" name="password"/><br/>
<input type="submit" name="submit" value="Register">
</form>
</body>
</html>
From postman when I do a POST to http://localhost:3000/api/users it works, but I want to do it when I submit the form and that's what I don't know how to do it. When I submit the form it reminds loading forever waiting to do something... how can I make a post of this data into de database from node.js?
Anyone can help me with this?
Thank you very much!
You need to call the DAO methods from the route handler and on callback from DAO method, you should send success or failure response to your client side.
For more information, you may look at -
This article
Hope this will help you
Thanks
Use this method:
db.collection.insert();
http://docs.mongodb.org/manual/reference/method/db.collection.insert/