Insert data from form into MYSQL using Node JS - html

I am trying inserting the data into MySQL using node and Express framework from a HTML form. The code for the form is :
<html>
<head>
<title>Personal Information</title>
</head>
<body>
<div id="info">
<h1>Personal Information</h1>
<form action="/myaction" method="post">
<label for="name">Name:</label>
<input type="text" id="name" name="name" placeholder="Enter your full name" />
<br><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email" placeholder="Enter your email address" />
<br><br>
<label for="city">City:</label>
<input type="text" id="city" name="city" placeholder="Enter your city" />
<br><br>
<label for="pincode">Pincode:</label>
<input type="text" id="pincode" name="pincode" placeholder="Enter your pincode" />
<br><br>
<input type="submit" value="Send message" />
</form>
</div>
</body>
</html>
and the .js file is :
var express = require('express');
var app = express();
var ejs = require('ejs');
var mysql = require('mysql');
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
var HOST = 'localhost';
var PORT = 3000
var MYSQL_USER = 'root';
var MYSQL_PASS = 'jelly123#';
var DATABASE = 'form';
var TABLE = 'info';
var mysql = mysql.createConnection({
host: HOST,
port: PORT,
user: MYSQL_USER,
password: MYSQL_PASS,
});
app.get('/home',function(req,res,next){
res.sendfile('views/forms.html');
});
app.post('/myaction', function(req, res) {
console.log('req.body');
console.log(req.body);
res.write('You sent the name "' + req.body.name+'".\n');
res.write('You sent the Email "' + req.body.email+'".\n');
res.write('You sent the City "' + req.body.city+'".\n');
res.write('You sent the Pincode "' + req.body.pincode+'".\n');
res.end()
mysql.query("Insert into "+TABLE+" (name,email,city,pincode) VALUES ('"+req.body.name+"','"+req.body.email+"','"+req.body.city+"','"+req.body.pincode+"')",function(err, result)
{
if (err)
throw err;
});
});
app.listen(3000);
console.log('Example app listening at port:3000');
I am able to enter the form data and display it in the page http://localhost:3000/myaction but unable to Insert data into database Please mention where I am doing wrong.
Thanks in advance.

var express = require('express');
var app = express();
var ejs = require('ejs');
var pg = require('pg');
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
var conString = process.env.DATABASE_URL || "postgres://postgres:Emdsystems#localhost:5432/student";
var client = new pg.Client(conString);
client.connect();
app.get('/',function(req,res,next){
res.sendfile('views/forms.html');
});
app.post('/myaction', function(req, res) {
console.log('req.body');
console.log(req.body);
res.write('You sent the name "' + req.body.name+'".\n');
res.write('You sent the Email "' + req.body.email+'".\n');
res.write('You sent the City "' + req.body.city+'".\n');
res.write('You sent the Pincode "' + req.body.pincode+'".\n');
res.end()
client.query("Insert into record (name,email,city,pincode) VALUES ('"+req.body.name+"','"+req.body.email+"','"+req.body.city+"','"+req.body.pincode+"')",function(err, result)
{
if (err)
throw err;
});
});
app.listen(3000);
console.log('Example app listening at port:3000');

try this
mysql.query('select id, name, price from ' + TABLE + ' where price < 100',
function(err, result, fields) {
if (err) throw err;
else {
console.log('Gadgets which costs less than $100');
console.log('----------------------------------');
for (var i in result) {
var gadget = result[i];
console.log(gadget.name +': '+ gadget.price);
}
}
});
reference: http://www.hacksparrow.com/using-mysql-with-node-js.html

This my js file-
var express = require("express");
var app = express();
var path = require("path");
var mysql = require('mysql');
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "mydb"
});
app.get('/',function(req,res){
res.sendFile(path.join(__dirname+'/index.html'));
});
app.post('/submit',function(req,res){
var name=req.body.name;
var email=req.body.email;
var username=req.body.username;
res.write('You sent the name "' + req.body.name+'".\n');
res.write('You sent the email "' + req.body.email+'".\n');
res.write('You sent the username "' + req.body.username+'".\n');
con.connect(function(err) {
if (err) throw err;
var sql = "INSERT INTO form (name, email,description) VALUES ('"+name+"', '"+email+"','"+username+"')";
con.query(sql, function (err, result) {
if (err) throw err;
console.log("1 record inserted");
res.end();
});
});
})
app.listen(3000);
console.log("Running at Port 3000");
This my html file-
<html>
<head>
<title> test </title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<form action="/submit" method="POST">
<fieldset>
<label for="name">Name: </label>
<input type="text" id="name" name="name" autofocus />
<br/>
<label for="email">Email: </label>
<input type="email" id="email" name="email" />
<br/>
<label for="username">User name: </label>
<input type="textbox" id="username" name="username" />
<br/>
<input type="submit" value="create profile" />
</fieldset>
</form>
</body>
</html>

You can try this
i am doing this with express js in node
pre-requisites:install node js,mysql,express,express-generator
Write this in index.jade file
<html>
<head>
<title> test </title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<form action="/submitform/" method="POST">
<fieldset>
<label for="name">Name: </label>
<input type="text" id="name" name="name" autofocus />
<br/>
<label for="email">Email: </label>
<input type="email" id="email" name="email" />
<br/>
<label for="description">Description: </label>
<textarea id="description" name="description"></textarea>
<br/>
<input type="submit" value="create profile" />
</fieldset>
</form>
</body>
</html>
Than ,write this in index.js file
var express = require('express');
var router = express.Router();
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "testn"
});
router.post('/submitform', function(req, res, next) {
console.log(req.body.name);
console.log(req.body.email);
console.log(req.body.description);
con.connect(function(err) {
if (err) throw err;
console.log("connected");
var sql = "INSERT INTO `form`(`name`,`email`, `description`) VALUES ('"+req.body.name+"','"+req.body.email+"','"+req.body.description+"')";
con.query(sql, function(err, result) {
if(err) throw err;
console.log("table created");
});
});
res.render('index', { title: 'Express' });
});
module.exports = router;
This code will insert values from form into MySql in node js
Hope this will help you

index.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Registration Form</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<style>
.error{
color: red;
font-style: italic;
}
</style>
</head>
<body>
<button type='text' class="btn btn-primary" id="showbtn">Show/Hide Form</button>
<div class = "container">
<div class = "col-md-6 col-md-offset-3">
<div class = "panel panel-primary">
<div class = "panel-heading">
Registration
</div>
<div class = "panel-body">
<form id = "registration" action="http://127.0.0.1:7744/register">
<input type = "text" class = "form-control" name = "username" placeholder = "Username"/>
<br/>
<input type = "text" class = "form-control" name = "email" placeholder = "Email"/>
<br/>
<input type = "password" class = "form-control" name = "password" placeholder = "Password" id = "password"/>
<br/>
<input type = "password" class = "form-control" name = "confirm" placeholder = "Confirm Password"/>
<br/>
<input type = "text" class = "form-control" name = "fname" placeholder = "First Name"/>
<br/>
<input type = "text" class = "form-control" name = "lname" placeholder = "Last Name"/>
<br/>
<div class = "gender">
<label class="radio-inline"><input type="radio" value="male" name="gender" class = "form-contorl"/>Male</label>
<label class="radio-inline"><input type="radio" name="gender" value="female" class = "form-contorl"/>Female</label>
</div>
<br/>
<select class = "form-control" name = "city">
<option value="0" selected="" disabled="">--SELECT--</option>
<option>Delhi</option>
<option>Ghaziabad</option>
<option>Noida</option>
<option>Faridabad</option>
<option>GuruGram</option>
</select>
<br/>
<textarea class = "form-control" name = "address" placeholder="Address"></textarea>
<br/>
<button type = "submit" class = "btn btn-primary" >Submit</button>
</form>
</div>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jquery-validation#1.19.3/dist/jquery.validate.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script> $(document).ready(function () {
jQuery.validator.addMethod("noSpace", function (value, element) {
return value == '' || value.trim().length != 0;
}, "No space please and don't leave it empty");
jQuery.validator.addMethod("customEmail", function (value, element) {
return this.optional(element) || /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(value);
}, "Please enter valid email address!");
$.validator.addMethod("alphanumeric", function (value, element) {
return this.optional(element) || /^\w+$/i.test(value);
}, "Letters, numbers, and underscores only please");
var $registrationForm = $('#registration');
if ($registrationForm.length) {
$registrationForm.validate({
rules: {
username: {
required: true,
alphanumeric: true
},
email: {
required: true,
customEmail: true
},
password: {
required: true
},
confirm: {
required: true,
equalTo: '#password'
},
fname: {
required: true,
noSpace: true
},
lname: {
required: true,
noSpace: true
},
gender: {
required: true
},
country: {
required: true
},
address: {
required: true
}
},
messages: {
username: {
required: 'Please enter username!'
},
email: {
required: 'Please enter email!',
email: 'Please enter valid email!'
},
password: {
required: 'Please enter password!'
},
confirm: {
required: 'Please enter confirm password!',
equalTo: 'Please enter same password!'
},
fname: {
required: 'Please enter first name!'
},
lname: {
required: 'Please enter last name!'
},
country: {
required: 'Please select country!'
},
address: {
required: 'Please enter address!'
}
},
errorPlacement: function (error, element) {
if (element.is(":radio")) {
error.appendTo(element.parents('.gender'));
}
else {
error.insertAfter(element);
}
}
});
}else{
alert("submitted");
}
$('#showbtn').click(function () {
$('.container').fadeToggle('slow');
});
});
</script>
</body>
</html>
index.js Server
var express = require('express');
var app = express();
var mysql = require('mysql');
var connection = mysql.createConnection({
host: '127.0.0.1',
user: 'root',
password: '',
database: 'node_form'
});
connection.connect();
app.get('/', function (req, res) {
res.sendFile(__dirname + "/" + "index.html");
})
app.get('/register', function (req, res) {
var fname = req.query.fname;
var lname = req.query.lname;
var username = req.query.username;
var gender = req.query.gender;
var email = req.query.email;
var city = req.query.city;
var password = req.query.password;
var address = req.query.address;
var confirm = req.query.confirm;
var check = "select * from registration where email = '" + email + "' or username = '" + username + "'";
connection.query(check, function (err, result) {
if (err) {
throw err;
} else if (result.length !== 0) {
console.log("user already exist");
}
else {
var user = {
fname: fname,
lname:lname,
username:username,
gender:gender,
email:email,
city:city,
password:password,
address:address
};
if (password !== confirm) {
console.log("password and confirm password not match")
} else {
connection.query('insert into registration set ?', user, function (err, rs) {
if (err) throw err;
console.log('Form submitted successfully');
res.sendFile(__dirname + "/" + "index.html");
})
}
}
})
})
var server = app.listen(7744, function () {
console.log("server started");
})

Related

React, Node Express, Mysql registration form stuck

I'm learning how to connect my front end to a database using middleware and trying to clone a waiver/registration form for a project my buddy gave me.
I can manually input data from the code editor to Mysql database but once I try to link it to the front end I get nothing, I'm completely stumped, can't really find any updated documentation on Node express syntax and mysql.
Here is my server and database code:
const express = require("express");
const app = express();
const mysql = require("mysql");
const bodyParser = require("body-parser");
const cors = require("cors");
const db = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "cloneDataBase",
});
app.use(express.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.get("/api/get", (req, res) => {
const sqlGet = "SELECT * FROM customer_registration";
db.query(sqlGet, (error, result) => {
res.send(result);
});
});
app.post("/api/post", (req, res) => {
const { firstName, lastName, email, phone, nickName } = req.body;
const sqlInsert =
"INSERT INTO customer_registration (firstName, lastName, email, phone, nickName) VALUES (?,?,?,?,?)";
db.query(
sqlInsert,
[firstName, lastName, email, phone, nickName],
(error, result) => {
if (error) {
console.log(error);
}
}
);
});
heres my registration form.
import React, { useState } from "react";
import "./NewCustomer.css";
import { Link, useNavigate } from "react-router-dom";
import { toast } from "react-toastify";
import axios from "axios";
const initialState = {
firstName: "",
lastName: "",
email: "",
phone: "",
nickName: "",
};
export default function NewCustomer() {
const [state, setState] = useState(initialState);
const { firstName, lastName, email, phone, nickName } = state;
const navigate = useNavigate();
const handleSubmit = (e) => {
e.preventDefalut();
if (!firstName || !lastName || !email || !phone || !nickName) {
toast.error("Please Provide value into each input field");
} else {
axios
.post("http://localhost:3001/api/post", {
firstName,
lastName,
email,
phone,
nickName,
})
.then(() => {
setState({
firstName: "",
lastName: "",
email: "",
phone: "",
nickName: "",
});
})
.catch((err) => toast.error(err.response.data));
setTimeout(() => navigate.push("/"), 500);
}
};
// const handleInputChange = (e) => {
// const { name, value } = e.target;
// setState({ ...state, [name]: value });
// };
return (
<div className="container">
<div className="new-customer-reg">
<Link to="/">
<button className="center-button-startover">Start Over</button>
</Link>
<div className="form-in">
<form onSubmit={handleSubmit} className="new-customer-form">
<label for="firstName">First Name*</label>
<input
type="text"
name="first_name"
required
// value={firstName}
// onChange={handleInputChange}
/>
<br />
<label for="lastName">Last Name*</label>
<input
type="text"
name="last_name"
required
// value={lastName}
// onChange={handleInputChange}
/>
<br />
<label for="email">Email*</label>
<input
type="email"
className="email"
required
// value={email}
// onChange={handleInputChange}
/>
<br />
<label for="phone">Phone*</label>
<input
type="tel"
className="phone"
required
// value={phone}
// onChange={handleInputChange}
/>
<br />
<label for="nickName">Nickname</label>
<input
type=" text"
className="nickname"
// value={nickName}
// onChange={handleInputChange}
/>
<div className="input-with-optional">
<span className="nick-helper">
(optional) This will be displayed instead of your first name.
</span>
<br />
</div>
<button onSubmit={handleSubmit} type="submit" className="regi">
Register
</button>
</form>
</div>
</div>
</div>
);
}enter code here
You forgot to send a response from your POST route handler. For example:
res.send('Customer created')
Additionally, in your frontend you have a typo (preventDefalut) which will make your code crash.

Can't insert data forms to sql server using electron

Whenever I click the submit button, it won't transfer the data to mssql.
It seems like it only works on hard-coded query with onload events without the web forms.
HTML
<form>
First Name:<input type="text" id="first_name" required="true"/>
Last Name: <input type="text" id="last_name" required="true"/>
<button onclick="formdata()"> Submit </button>
</form>
Javascript
function formdata(){
var sql = require('mssql');
var config = {
userName: 'username',
password: 'password',
server: 'server',
database: 'database',
options: {
instanceName: 'instancename'
, encrypt: false
}
};
sql.connect(config, function (err) {
if (err) console.log(err);
var request = new sql.Request();
var fn = document.getElementById('first_name').value;
var ln = document.getElementById('last_name').value;
request.query('execute sp_tmp_name fn,ln');
});
}
Updated
I finally work it out. I included the ipcmain and ipcrenderer part to make it work.
Forms js
const ipcRenderer = require('electron').ipcRenderer;
function formdata(event){
event.preventDefault()
let fn = document.getElementById('first_name').value;
let ln = document.getElementById('last_name').value;
ipcRenderer.send('form-submission', fn,ln)
//pass ipcRenderer data to ipcmain
}
Main js
const {app, BrowserWindow, ipcMain} = require('electron')
........
ipcMain.on('form-submission', function (event, first_name,last_name) {
event.preventDefault()
var sql = require('mssql');
const pool = new sql.ConnectionPool({
user: 'xxxx',
password: 'xxxx',
server: 'xxxx',
database: 'xxxx',
options: {
instanceName: 'xxxx'
, encrypt: false
}
})
var conn = pool;
conn.connect().then(function () {
var request = new sql.Request(conn);
request.query("execute sp_tmp_name_sample" +" "+ first_name +","+last_name).then(function (recordset) {
console.log(recordset);
conn.close();
})
.catch(function (err) {
console.log(err);
conn.close();
});
});
})
HTML
<form action="#" method="post" name="ipcForm">
First Name:<input type="text" id="first_name" name="first_name" placeholder="First Name" required="true"/>
Last Name: <input type="text" id="last_name" name="last_name" placeholder="Last Name" required="true"/>
<input type="button" value="Submit" onclick="formdata(event)"/>
</form>
<script src="forms.js"></script>

Sending data from html form to mysql table using node.js

I am trying to send data from my form to mysql database. My table has three columns minus the id column
This is the html for the form:
<!DOCTYPE html>
<html lang="en">
<head>
<title>contact form</title>
</head>
<body>
<div id="page">
<form method="post" action="/myaction">
<label for="name">Enter name: </label>
<input id="name" type="text" name="name" value="<%= qs.person %>"> <br><br>
<label for="age">Enter age: </label>
<input id="age" type="number" name="age" value="<%= qs.year %>"><br><br>
<label for="department">Enter department: </label>
<input id="dept" type="text" name="department" value="<%= qs.dept %>"><br><br>
<input type="submit" value="OK">
</form>
<!--site javascript included-->
<script src="jquery-3.2.0.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script type="text/javascript" src="site.js"></script>
</div>
</body>
</html>
this is my node.js code, app.js:
var http = require('http');
var mysql = require('mysql');
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.set('view engine', 'ejs');
var urlencodedParser = bodyParser.urlencoded({ extended: false });
var con = mysql.createConnection({
host: "localhost",
user: "Name",
password: "XXXXXXXXXXXX",
database: "mydb"
});
app.get('/contact', function (req, res) {
res.render('contact', { qs: req.query });
});
app.post('/myaction', urlencodedParser, function (req, res) {
console.log(req.body);
var name = req.body.name;
var age = req.body.age;
var department = req.body.department;
con.connect(function (err) {
if (err) throw err;
console.log("connected");
var sql = "INSERT INTO 'customers' (name, age, department) VALUES (name, age, department)";
con.query(sql, function (err) {
if (err) throw err;
console.log("One record inserted");
});
});
res.render('contact-success', { data: req.body });
});
app.listen(3000, function () {
console.log('server running on port 3000');
});
When I enter some values into my form and run it, I get this error:
Error: ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''customers' (name, age,
department) VALUES (name, age, department)' at line 1
I'm finding it difficult to figure it out. Any help please!!!
You should not add quotes around the table name.
Check on this.

how to insert data into database using MEAN stack (MySQL, Express, Angular, Node)

How to insert data into database using MEAN stack (MySQL, Express, Angular, Node)?
I am facing the problem at the time of insertion. Please help me to solve this. Here is my code. I'm newbie in MEAN.
index.html
<html ng-app="bookitnow">
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<title> Registration Page </title>
</head>
<body>
<div class="container" ng-app="bookitnow" ng-controller="myCtrl">
<h1>Register</h1>
<form method="post">
<div class="form-group">
<input type="text" class="form-control" id="firstName" ng-model="fname" placeholder="First Name" required>
</div>
<div class="form-group">
<input type="text" class="form-control" id="lastName" ng-model="lname" placeholder="Last Name" required>
</div>
<div class="form-group">
<input type="email" class="form-control" id="email" ng-model="email" placeholder="Email Address" required>
</div>
<div class="form-group">
<input type="text" class="form-control" id="phone" ng-model="phone" placeholder="Phone" required>
</div>
<button type="submit" class="btn btn-info" ng-click="submit()">Submit</button>
</form>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
<script src="controllers/controller.js"></script>
</body>
</html>
server.js
var express = require("express");
var app = express();
var bodyParser = require('body-parser');
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'bookitnow'
});
connection.connect(function(err) {
if (!err)
console.log('Database is connected');
else
console.log('DB connection error.');
});
app.use(express.static(__dirname + '/public'));
app.get('/index.html', function(req, res){
res.sendFile(__dirname + '/public' + 'index.html');
});
app.post('/index.html', function(req, res, next) {
var data = req.body;
console.log('request received:', data);
connection.query('INSERT INTO register SET ?', data, function(err,res){
if(err) throw err;
console.log('record inserted');
});
app.listen(5500);
console.log('Hi from server.js');
controller.js
var app = angular.module('bookitnow',[]);
app.controller('myCtrl', function($scope,$http){
$scope.submit = function() {
var data = {
fName : $scope.fname,
lName : $scope.lname,
email : $scope.email,
phone : $scope.phone
}
};
$http.post('/index.html', &scope.data)
.success(function (data, status, headers, config) {
$scope.result = data;
console.log("inserted successfully")
})
.error(function(data, status, header, config){
$scope.result = "Data: " + status;
});
In your controller.js, try the following and see what happens.
var app = angular.module('bookitnow',[]);
app.controller('myCtrl', function($scope, $http){
$scope.submit = function() {
var data = {
fName : $scope.fname,
lName : $scope.lname,
email : $scope.email,
phone : $scope.phone
};
$http
.post('/index.html', data)
.then(function (response) {
console.log(response)
}, function(response){
console.log(response)
});
};
});

how to fill a mysql database from a data entries of a form?

I try to fill a data-base when a person create an account.My server is in node.js.
app.js:
var http=require("http");
var express = require('express');
var app = express();
var server = http.createServer(app);
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var bcrypt = require('bcrypt-nodejs');
var ejs = require('ejs');
var path = require('path');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
// routes
var route = require('./route');
// model
var Model = require('./model');
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(cookieParser());
app.use(bodyParser.urlencoded({extended:false}));
app.use(session({secret: 'secret strategic xxzzz code',
resave:false,
saveUninitialized:false
}));
app.use(passport.initialize());
app.use(passport.session());
server.listen(3000,function(){
console.log("server listen at localhost:3000");});
passport.use(new LocalStrategy(function(username, password, done) {
new Model.User({username: username}).fetch().then(function(data) {
var user = data;
if(user === null) {
return done(null, false, {message: 'Invalid username or password'});
} else {
user = data.toJSON();
if(!bcrypt.compareSync(password, user.password)) {
return done(null, false, {message: 'Invalid username or password'});
} else {
return done(null, user);
}
}
});
}));
passport.serializeUser(function(user, done) {
done(null, user.username);
});
passport.deserializeUser(function(username, done) {
new Model.User({username: username}).fetch().then(function(user) {
done(null, user);
});
});
// signup
// GET
app.get('/signup', route.signUp);
// POST
app.post('/signup', route.signUpPost);
route.js:
var signUpPost = function(req, res, next) {
var user = req.body;
var usernamePromise = null;
usernamePromise = new Model.User({username: user.username}).fetch();//verify the existence of username on the database
return usernamePromise.then(function(model) {
if(model) {
res.render('index1', {title: 'Index', errorMessage: 'username already exists'});//verify if the entered username exists in the databas.
} else {
var password = user.password;
var email=user.email;
if(password.length<5){
res.render('index1',{title:'index',errorMessage:'password so weak'});//password must been > 5 caracters.
}
else if(verifMail(email) === false){
res.render('index1',{title:'index',errorMessage:'email invalid'});//if the email is not valid,it show an error
}
else{
var hash = bcrypt.hashSync(password);//crypt the password
var signUpUser = new Model.User({username: user.username, password:hash,email:user.email,firstname:user.firstname,lastname:user.lastname});//add a new row in the database
signUpUser.save().then(function(model) {
signInPost(req, res, next);
});
};
}
});
};
Model.js:
var DB = require('./db').DB;
var User = DB.Model.extend({
tableName: 'newuser',
idAttribute: 'userId',
});
module.exports = {
User: User
};
db.js:
var Bookshelf = require('bookshelf');
var config = {
host: 'localhost',
user: 'root',
password: '',
database: 'Users',
charset: 'UTF8_GENERAL_CI'
};
var DB = Bookshelf.initialize({
client: 'mysql',
connection: config
});
module.exports.DB = DB;
When a person click a button to signup,a modal display to enter his firstname,lastname,email and password.
<div id="myModal" class="modal fade" role="dialog" >
<div class="model-content">
<div class="modal-header" >
<button type="button" class="close" data-dismiss="modal">×</button>
<h3 id="myModalLabel">Modal header</h3>
</div>
<div class="modal-body">
<!-- form -->
<form id="register-form" role="form" method="post" action="/signup">
<div class="form-group">
<input type="text" class="form-control" id="username" placeholder="User name">
</div>
<div class="form-group">
<input type="text" class="form-control" id="firstname" placeholder="First name">
</div>
<div class="form-group">
<input type="text" class="form-control" id="lastname" placeholder="Last name">
</div>
<div class="form-group">
<input type="email" class="form-control" id="email" placeholder="Email">
</div>
<div class="form-group">
<input type="password" class="form-control" id="password" placeholder="Password">
</div>
<div class="emaillogin">
<button type="submit" class="btn btn-default email-signin-button">
Submit
</button>
</div>
</form>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-default email-signin-button" data-dismiss="modal">
Close
</button>
</div>
</div>
</div>
The page still reload for a long time and the data did not been saved in the database.
Your signUpPost function should return a view or redirect to another route but it returns a promise instead.
Besides a then() function should always return a promise or a value but it returns nothing. And you should always add a catch block;
I think you misunderstood the way Promises work.
//...
usernamePromise.then(function(model) {
if ( model ) throw new Error('username already exists');
else {
//...
if( ...) { throw new Error('password so weak'); }
else if( ...) { throw new Error('email invalid'); }
else {
//...
return signUpUser.save();
}
}
}).then(function(model){
// do what you want with model and redirect
return res.redirect('/my/new/route');
}).catch(function(err){
// do what you want with err (eg: use flash or console.log(err)) and redirect
return res.redirect('/my/new/route');
});
//...