Express.js not adding into mysql - mysql

I'm a beginner to ExpressJS, I want to be able to add records to the "site" table. However, when I run the following code, it says:
Error: ER_BAD_FIELD_ERROR: Unknown column 'BeastMode' in 'field list'.
"BeastMode" is an entry I made to the shortName field.
A little context: I'm not supposed to use ORM. I have to use raw sql queries to add to MYSQL database.I'm using 'mysql'package for Nodejs to connect to the database.
var squery = "INSERT INTO SITE (shortName,addressLine1,addressLine2,city,state,zipcode,phoneNumber) VALUES "+
"("+
req.body.shortName+", "+
req.body.addressLine1+", "+
req.body.addressLine2+", "+
req.body.city+", "+
req.body.state+", " +
req.body.zipcode+", " +
req.body.phoneNumber+" );"
console.log(req.body);
dbconnector.query(squery,function(err,rows,fields){
if(!err){
res.send("Record Added Successfully: "+req.body);
}else{
res.send("Error: "+ err);
}
});
});
Also, here is my dbconnect.js file:
var mysql = require('mysql');
dbconnect = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database:"rsacs"
});
module.exports = dbconnect
Here is my HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<% include head %>
</head>
<body class="container">
<header>
<% include header %>
</header>
<main>
<div>
<h1><%=title%></h1>
<form method="post" action="/site/create" >
<div class="form-group">
<label for="shortName">Shortname</label>
<input type="text" class="form-control" placeholder="Shortname" name="shortName"><br>
<label for="Address Line 1"> Address Line 1:</label>
<input type="text" class="form-control" placeholder="Address Line 1" name="addressLine1"><br>
<label for="Address Line 2"> Address Line 2:</label>
<input type="text" class="form-control" placeholder="Address Line 2" name="addressLine2"><br>
<label for="City">City:</label>
<input type="text" class="form-control" placeholder="City" name="city"><br>
<label for="State">State:</label>
<input type="text" class="form-control" placeholder="State" name="state"><br>
<label for="Zipcode">Zipcode:</label>
<input type="text" class="form-control" placeholder="Zipcode" name="zipcode"><br>
<label for="PhoneNumber">Phone Number:</label>
<input type="text" class="form-control" placeholder="PhoneNumber" name="phoneNumber"><br>
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
</div>
</main>
<footer>
<% include footer %>
</footer>
</body>
</html>
Here is my Site table structure

To echo #AnshumanJaiswal's solution, you're probably encountering an escape character problem.
The solution I'm going to propose, though, is different. The mysql nodejs driver supports prepared queries. As such, the most robust way to sort your query is:
var squery = "INSERT INTO SITE (shortName,addressLine1,addressLine2,city,state,zipcode,phoneNumber) VALUES (?,?,?,?,?,?,?);
var objs = [req.body.shortName,req.body.addressLine1,req.body.addressLine2,req.body.city,req.body.state,req.body.zipcode,req.body.phoneNumber]
sql = mysql.format(squery, objs);
// now you have a properly-escaped SQL query which you can execute as usual:
connection.query(squery, objs, function (error, results, fields) {if (error) throw error;});
Let me know if this doesn't sort your problem.

the values are string and you are not passing them as string.
There are two possible ways:
Solution 1.
add `` to your string values like:
var squery = "INSERT INTO SITE (shortName,addressLine1,addressLine2,city,state,zipcode,phoneNumber) VALUES "+
"('"+
req.body.shortName+"', '"+
req.body.addressLine1+"', '"+
req.body.addressLine2+"', '"+
req.body.city+"', '"+
req.body.state+"', '" +
req.body.zipcode+"', " +
req.body.phoneNumber+" );"
...
Solution 2.
make an object from body data as:
var data = {
shortName: req.body.shortName,
addressLine1: req.body.addressLine1,
addressLine1: req.body.addressLine2,
city: req.body.city,
state: req.body.state,
zipcode: req.body.zipcode,
phoneNumber: req.body.phoneNumber
};
var squery = "INSERT INTO SITE SET ?";
dbconnector.query(squery, data, function(err,rows,fields){
if(!err){
console.log(rows);
res.send("Record Added Successfully.");
}else{
res.send("Error: "+ err);
}
});

Related

How to pass data from html client to NodeJS server?

I would like to send some data from client to NodeJS server using POST method.
Below is my part of html code.
<form action="http://localhost:8080/data/name/:name/ssn/:ssn" method="post" id="signup">
<h1>Personal info post example</h1>
<div class="field">
<label for="name">Name:</label>
<input type="text" id="name" placeholder="Enter your fullname" />
<small></small>
</div>
<div class="field">
<label for="ssn">SSN:</label>
<input type="text" id="ssn" placeholder="Enter your SSN" />
<small></small>
</div>
<button type="submit">Submit</button><br><br>
</form>
Below is my part of server.js.
I tried to print out everything that I can think of what I can.
I wrote down the results as comments as well.
This is the result when I enter 'a' for the name and 'b' for the ssn and submit it.
app.post('/data/name/:name/ssn/:ssn', function(req, res) {
console.log('req.query: ', req.query); // {}
console.log('req.query.name: ',req.query.name); // undefined
console.log('req.query.ssn: ',req.query.ssn); // undefined
console.log('req.params: ',req.params); // { name: ':name', ssn: ':ssn' }
console.log('req.params.name: ',req.params.name); // :name
console.log('req.params.ssn: ',req.params.ssn); // :ssn
});
When I type 'a' and 'b' into search boxes and hit the submit button, the web browser starting to load but never ends and my VSC shows the result.
Can anyone help me what I need to fix?
looks like you're mixing req.params and req.query, while you actually need req.body
try this:
add this to server.js (you need to install body-parser):
const bodyParser = require('body-parser');
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }));
// parse application/json
app.use(bodyParser.json());
app.post('/data', function(req, res) {
console.log('req.body: ', req.body);
const {name, ssn} = req.body;
console.log('name: ', name);
console.log('ssn: ', ssn);
res.json(req.body);
});
and change HTML form (add name attribute, that's your data):
<form action="http://localhost:8080/data" method="post" id="signup">
<h1>Personal info post example</h1>
<div class="field">
<label for="name">Name:</label>
<input type="text" id="name" name="name" placeholder="Enter your fullname" />
<small></small>
</div>
<div class="field">
<label for="ssn">SSN:</label>
<input type="text" id="ssn" name="ssn" placeholder="Enter your SSN" />
<small></small>
</div>
<button type="submit">Submit</button><br><br>
</form>
your code is good. But you are facing this problem because the server is not sending any data after submit.
First, there should be something to handle GET:
var express = require('express');
var app = express();
app.get('/', (req, res)=>{
res.sendFile('index.html');
console.log('Someone saw your website!');
})
app.listen(80);
Secondly, return something after submit:
app.post('/data/name/:name/ssn/:ssn', function(req, res) {
console.log('req.query: ', req.query); // {}
console.log('req.query.name: ',req.query.name); // undefined
console.log('req.query.ssn: ',req.query.ssn); // undefined
console.log('req.params: ',req.params); // { name: ':name', ssn: ':ssn' }
console.log('req.params.name: ',req.params.name); // :name
console.log('req.params.ssn: ',req.params.ssn); // :ssn
res.end('Thankyou, \n Your Name:'+req.params.name+'\n Your Ssn:'+req.params.ssn);
});

Write down user input in a text file

i tryed it with a basic html code like :
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname" value="John"><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname" value="Doe"><br><br>
<input type="submit" value="Submit">
</form>
but then the input is saved like fname=John&lname=Doe
I wrote a script in python that gets the file xxx/xxx/display.txt
when i use the basic html input function, the text will get saved as fname =john & sname=rober
what i woud need is the string to get saved as john rober
how can i write the input down in the txt file without = and & , and how do i save it in the file, while overwriting everything previus in the txt file?
For that you need your js-code to be server side. I'd reccoment Node.js for that.
Than we need to format the input with js:
// Requiring fs module in which writeFile function is defined:
const fs = require('fs');
var fname = document.getElementById("fname").value;
var lname = document.getElementById("lname").value;
var fullname = fname + lname;
// data which will write in a file
let data = fullname;
// Write "data" in "file.txt":
fs.writeFile('file.txt', data, (err) => {
// In case of an error trhow err:
if (err) throw err;
})

How to display the response data in a input text field of a form in a html?

I am really new to node.js and do have a problem. I want to show the data from the logged in user in these inputfields.
I can access to the data of the logged in user by following code and can show it also on the console:
Output on console
Here is the code on the server-side:
app.post('/aender', function (req, res) {
res.send(req.session.username);
res.send(req.session.name);
res.send(req.session.email);
var sql = "UPDATE user SET name ='" + [req.body.name] + "', username='" + [req.body.username] + "', email='" + [req.body.email] + "', password='" + [req.body.password] + "' WHERE user_ID='" + [req.session.user_id] + "'";
if(req.body.password === req.body.password2) {
db.query(sql, (err, result) => {
if (err) throw err;
console.log("Daten erfolgreich geaendert");
res.redirect('/aender');
});
}else{
res.redirect('/aender');
}
});
Here is the HTML-Code:
<!doctype html>
<html>
<h2 class="page-header">Registrierung</h2>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="../app.js"></script>
<form id ="form1" action="/aender" method="post">
<div class="form-group">
<label>Name</label>
<input type="text" class="form-control" placeholder="Name" name="name" id ="name">
</div>
<div class="form-group">
<label>Username</label>
<input type="text" class="form-control" placeholder="username" name="username" id ="username">
<script>
displayUserData()
</script>
</div>
<div class="form-group">
<label>Email</label>
<input type="email" class="form-control" placeholder="Email" name="email" id ="email" pattern="(^[a-zA-Z0-9_-]{1,20}#[a-zA-Z0-9]{1,20}.[a-zA-Z]{2,3}$)">
</div>
<div class="form-group">
<label>Password</label>
<input type="password" class="form-control" placeholder="Password" name="password" pattern="(?=.*[a-zA-Zd!##$%^&*()-_+={}[]|;:<>,./?]).{6,}">
</div>
<div class="form-group">
<label>Confirm Password</label>
<input type="password" class="form-control" placeholder="Password" name="password2" pattern="(?=.*[a-zA-Zd!##$%^&*()-_+={}[]|;:<>,./?]).{6,}">
</div>
<button type="submit" name="submit" class="btn btn-default">Profil ändern</button>
</form>
<form id ="form2" action="/loeschen" method="post">
<button type="submit" name="submit" class="btn btn-default">Konto löschen</button>
</form>
</html>
For example I do want to display the name, username and the e-mail of Max Mustermann, like that:
Data on Form
What you want to do is called interpolation and it is not directly possible in HTML. There are two possible options:
Create an API REST service omn the server side and do your call with ajax or jquery and then retrieve data (not the best option if you are not planning to have it for other purposes and not the best option in terms of security).
You can consider to switch to pug, which can be totally integrated with nodejs. Here is a practical example of interpolation with jade, which is the predecessor of pug.
if you want to do this with ajax you've first to change server logic:
app.post('/aender', function (req, res) {
var sql = "UPDATE user SET name ='" + [req.body.name] + "', username='" + [req.body.username] + "', email='" + [req.body.email] + "', password='" + [req.body.password] + "' WHERE user_ID='" + [req.session.user_id] + "'";
if(req.body.password === req.body.password2) {
db.query(sql, (err, result) => {
if (err) throw err;
console.log("Daten erfolgreich geaendert");
res.json({username:req.session.username,name:req.session.name,email:req.session.email});
});
}else{
res.redirect('/aender');
}
});
(Please note that i have just corrected the function in order to do that, but your logic is still broken, there's no sense at all to pass the session parameters).
Then in your html:
<script type="text/javascript">
$.post(/*hostname+*/ "/aender", function( data ) {
console.log(data); // {username:req.session.username,name:req.session.name,email:req.session.email}
})
</script>
This is not a full complete script, but it is a good start for you to adapt.

How to send data to HTML page and how to use AJAX for Single Page Application in NodeJS Server using express.js framework?

How can I display the form submitted data in another HTML Page
From 1st page (page1.html)collecting the data from users and after appending this data in the database I want to show the submitted values in another page i.e.(page4.html)
Below is my code
I have tried using res.sendFile or res.send
server.post('/addname', (req, res) => {
const user = {
timestamp: new Date,
FName: req.body.FName,
LName: req.body.LName,
Phone: req.body.Phone,
Email: req.body.email,
Contact: req.body.business,
Business: req.body.contact,
OTP: req.body.otp_field
}
res.sendFile(__dirname + '/page4.html');
//along with file rediraction, how can i send or show the "User" vaules in respactivte filed
});
<body>
<div>
<div align="center">
<form action="/addname" method="GET">
<label>Please enter below details</label><br><br>
<label>First Name *: </label><input id="FName" type="text" name="FName"/><br><br>
<label>Last Name *: </label><input id="LName" type="text" name="LName"/><br><br>
<label>Email Address *: </label><input type="email" name="email"><br><br>
<br><br>
<input type="submit" value="Submit" /></form>
</div>
</div>
</body>
nAs I can see in your code
<body>
<div>
<div align="center">
<form action="/addname" method="GET">
<label>Please enter below details</label><br><br>
<label>First Name *: </label><input id="FName" type="text" name="FName"/><br><br>
<label>Last Name *: </label><input id="LName" type="text" name="LName"/><br><br>
<label>Email Address *: </label><input type="email" name="email"><br><br>
<br><br>
<input type="submit" value="Submit" /></form>
</div>
</div>
</body>
Your form method is "GET", it should be "POST" as your API is "POST".
server.post('/addname', (req, res) => {
<form action="/addname" method="GET">
//Just change to
<form action="/addname" method="POST">
While sending and HTML file you need to send your submitted data too.
res.sendFile(__dirname + '/page4.html');
In order to save your hurdle switch to Single Page Application and use some JavaScript frame work like AngularJs, ReactJs or if not then also stick to single page and use Ajax calls for submit calls.
Else see "ejs" in place of "HTML" and use scriptlet to send and show data over HTML.
To send data to "ejs" via expressJs
res.render('show.ejs', {message});
With Ajax you can do this:
HTML
<body>
<div>
<div align="center">
<form id="form1">
<label>Please enter below details</label><br><br>
<label>First Name *: </label><input id="FName" type="text" name="FName"/><br><br>
<label>Last Name *: </label><input id="LName" type="text" name="LName"/><br><br>
<label>Email Address *: </label><input type="email" name="email"><br><br>
<br><br>
<input type="button" value="Submit" onClick:"submitForm()"/>
</form>
<div id="showValue"></div>
</div>
</div>
</body>
JavaScript
function submitForm() {
$.ajax({
url: '/addName',
type: 'POST',
headers: headers,
data: {
"Fname": $("#FName").val(),
"Lname": $("#LName").val(),
"email": $("#email").val()
},
success: function(result) {
//append result to your html
//Dynamic view
$("#form1").hide();
var html = '<div><span>First Name: ' + result.fName + '</span><span>Last Name: ' + result.lName + '</span></div>';
$("#showValue").html(html);
},
error: function (error) {
alert('error ',error);
}
});
}
Server side code I'm assuming you are using express.js and body-parser
app.post('/addName', (req, res) => {
//Insert into db
var body = req.body;
res.send({
fName: body.FName,
lName: body.LName
});
});

Offline and Online syncing with Web applications in HTML5?

I have a basic web application below that has a sqlite storage measure implemented into it.
I would like it to be able to update my mysql server anytime it is connected, and store values to push to the database after it has lost connection. I would like it to be able to
use a timestamp comparison as a safety measure, just in case values on the server differ, we can to a stamp check to see if what it is trying to alter IS the most current values.
(this will be run from multiple computers, so will need SOME kind of failsafe).
I believe that this transaction WILL only need to be one way though, the values just need to update the server, values will not need to be passed back to the application, so we could technically destroy the database upon a real completion, or possibly perform a rollback if it breaks somewhere. Is this a doable thing, or am I really asking to much here?
Here's a very basic app I'd like to use as a model.
<!DOCTYPE html>
<html>
<head>
<title>Golf score keeper</title>
<script src="http://www.google.com/jsapi"></script>
<script>
google.load("jquery", "1.4.1");
</script>
<script>
var db = window.openDatabase("scores", "", "Previous Scores", 1024*1000);
function insertScore(hole_num, num_strokes, course_id, email) {
db.transaction(function(tx) {
tx.executeSql('INSERT INTO Strokes (course_id, hole_num, num_strokes, email) VALUES (?, ?, ?, ?)', [course_id, hole_num, num_strokes, email]);
});
}
function renderResults(tx, rs) {
e = $('#previous_scores');
e.html("");
for(var i=0; i < rs.rows.length; i++) {
r = rs.rows.item(i);
e.html(e.html() + 'id: ' + r['id'] + ', hole_num: ' + r['hole_num'] + ', num_strokes: ' + r['num_strokes'] + ', email: ' + r['email'] + '<br />');
}
}
function renderScores(email) {
db.transaction(function(tx) {
if (!(email === undefined)) {
tx.executeSql('SELECT * FROM Strokes WHERE email = ?', [email], renderResults);
} else {
tx.executeSql('SELECT * FROM Strokes', [], renderResults);
}
});
}
$(document).ready(function() {
db.transaction(function(tx) {
tx.executeSql('CREATE TABLE IF NOT EXISTS Courses(id INTEGER PRIMARY KEY, name TEXT, latitude FLOAT, longitude FLOAT)', []);
tx.executeSql('CREATE TABLE IF NOT EXISTS Strokes(id INTEGER PRIMARY KEY, course_id INTEGER, hole_num INTEGER, num_strokes INTEGER, email TEXT)', []);
});
$('#score_form').submit(function() {
strokes = { 1: $('#hole1').val(), 2: $('#hole2').val() };
for (var hole_num in strokes) {
insertScore(hole_num, strokes[hole_num], 1, $('#email').val());
}
renderScores();
return false;
});
$('#filter_previous_scores_form').submit(function() {
e = $('#filter_by_email').val();
renderScores(e);
return false;
});
renderScores();
});
</script>
</head>
<body>
<form method="get" id="score_form">
<div>
<label for="1">Hole 1</label>
<input type="number" min="1" value="4" id="hole1" name="hole1" size="2" step="1" />
</div>
<div>
<label for="2">Hole 2</label>
<input type="number" min="1" value="4" id="hole1" name="hole2" size="2" step="1" />
</div>
<div>
<input type="email" id="email" placeholder="Enter your email address" size="40"/>
</div>
<div>
<input type="submit" value="Upload Score" />
</div>
</form>
<div>
<h2>Previous Scores</h2>
<form id="filter_previous_scores_form">
<input type="email" placeholder="Filter scores by email" size="40" id="filter_by_email" /><br />
<input type="submit" value="Filter" />
</form>
</div>
<div id="previous_scores">
</div>
</body>
</html>
You shoulg take a look at Ajax in a setInterval loop.
you can apply the logic of set interval when you found navigator.online=true then you can call ajax.