Validation in express Rest Apis - mysql

I am saving signup value into database using expressjs in Rest api but how can i valuate my fields (name,email,password) so if i save without data then error message related to field should show
Here is my code
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "mydb"
});
var toTime = new Date();
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
var sql = "INSERT INTO users (name, email,password) VALUES ('"+req.body.name+"','"+req.body.email+"','"+req.body.password+"')";
con.query(sql, function (err, result) {
if (err) throw err;
console.log("1 record inserted");
});
});

First note: you're code is susceptible to SQL injection. Refer: this SO question
Now, You can just make a validation function which returns booleanand use it before the query like
function validateFunc(...params){
return params.reduce((p,c)=> p && (c !== null && c !== undefined), true);
}
And use it like,
if(!validateFunc(req.body.name, req.body.email, req.body.password)){
// throw some error
}
var sql = "INSERT INTO users (name, email,password) VALUES ('"+req.body.name+"','"+req.body.email+"','"+req.body.password+"')";

Related

I want my query result to be displayed in format of actual table Node.js HTML CSS

I am building a project for Database Course.
I am already done with Front End. I built the front end using Tailwind CSS.
Now I've started working on the backend and getting data from the database and display on my website using Node.js
I am a beginner and I want the result of the query to be styled and formatted like an actual table.
So I need help as I didn't find a reliable solution on the internet
I AM ATTACHING THE OUTPUT RESULT AND THE KIND OF RESULT I WANT.
Here is my Node.js code
var mysql = require('mysql');
const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "12345678",
database: "mydb"
});
var sqlQuery = "SELECT username FROM Users";
con.connect(function (err) {
if (err) throw err;
console.log("Connected!");
// con.query(sqlQuery, function (err, result) {
// if (err) throw err;
// console.log(result);
// });
});
// display query result on host
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
// display query result on host
con.query(sqlQuery, function (err, result) {
if (err) throw err;
//show result in table format
res.end(JSON.stringify(result));
});
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
CURRENT OUTPUT
OUTPUT I WANT

How can I update data using NodeJS?

i want to update result prediction to database mysql, but data cannot save at database.
const periode = _.get(row, "periode", new Date());
const prediction =
b0 +
b1 * Number.parseFloat(_.get(row, "x1", 0)) +
b2 * Number.parseFloat(_.get(row, "x2", 0));
const sql = `UPDATE performance SET prediction_result="${prediction}" WHERE periode="${periode}"`;
db.query(sql, (error, results, fields) => {
if (error) {
console.error('An error occurred while executing the query')
throw error
}
})
i am getting error like this:
throw err; // Rethrow non-MySQL errors
ReferenceError: connection is not defined
Can you help me solve this problem?
You should have something like this in your code.
var mysql = require('mysql');
var db= mysql.createConnection({
host: "localhost",
user: "yourusername",
password: "yourpassword"
});
db.connect(function(err) {
if (err) throw err;
console.log("Connected!");
});

how can i insert data i got from api into mysql using nodejs?

con.connect(function(err) {
var aid = JSON.stringify(response.articles[1].author);
//if (err) throw err;
console.log("Connected!!!!!");
console.log(aid);
var sql = "INSERT INTO db1 (id,fname) VALUES (5,aid)";
if (err) throw err;
console.log("1 record inserted");
});
HERE IS MY CODE THAT IS NOT WORKING I AM USING BODY-PARSE AND EXPRESS TOO!!! but the error mentioned that in MySQL syntax how can i solve it ?
You can use Sequelize ORM for MySQL.
Sequelize Doc
Example Create Usage with ExpressJS
var username = req.body.username;
var password = req.body.password;
router.get('/create_user', (req,res) => {
user.create({
username,
password
}).then((usr) => {
res.send(usr)
})
})

Looping through JSON file and inserting into mysql database table using node.js

I have a number of values in a JSON file set out as follows:
[{"scraped_at": 1533384162.2934802, "server_id": "461235834994032661", "invite_code": "5uWt6B", "server_name": "Magic Pokemon", "members": ["115385224119975941", "133557837598031872"]}
As can be seen the last value is another array. I've been trying to use the following code to insert into the mysql database using node.js:
const fs = require('fs');
var obj;
const mysql = require('mysql');
const con = mysql.createConnection({
host: "localhost",
user: "root",
password: "root",
database: "list"
});
fs.readFile('list.json', 'utf8', function (err, data) {
if (err) throw err;
obj = JSON.parse(data);
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
for(var i = 0; i < obj.length; i++) {
const s_at = obj[i].scraped_at;
const s_id = obj[i].server_id;
const s_inv = obj[i].invite_code;
const s_sn = obj[i].server_name;
const mbs = obj[i].members;
const sql = 'INSERT INTO members (scraped_at, server_id, invite_code, server_name, servermbs) VALUES ('+s_at+','+s_id+','+s_inv+','+s_sn+','+mbs+')';
con.query(sql, function (err, result) {
if (err) throw err;
console.log("x record inserted");
});
}
});
});
I'm currently getting the following error thrown:
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 'RP,115385224119975941,133557837598031872,160105994217586689,212681528730189824,2' at line 1
Anyone got any ideas what is up with it and if so any solutions?
Apologies if the code doesn't look too great as I've never been good at formatting on this community site.
Thanks!

node.js mysql not returning results

I am working with socket.io and node.js developing login system, but getting error while I am authenticating user:
function checkUsername(username){
// console.log("checking username "+username+" in database");
var sql = "SELECT username FROM users where username = ?";
var checkUser;
//execute query
db.query(sql, [username], function (err, result,fields) {
if (err)
console.log(err);
else{
//gets found records length/quantity
checkUser = result.length;
console.log("username "+username+" result: "+checkUser);
return checkUser;
}
});
}
I'm getting undefined in return, in short there is nothing being returned.