Error inserting into users table in Node.js - mysql

I got the Failed to load resource: the server responded with a status of 500 (Internal Server Error)
in the // Error inserting into users table section.
What causes this problem? Where should I check? My database has all the mandatory fields. I am using SQL db.
function registerUser(rBody) {
const connection = mysqlConnection
return new Promise((resolve, reject) => {
// First attempt to has user password, and continue on success
bcrypt.hash(rBody.password, 10, (err, hash) => {
if (err) {
// Error crypting password
resolve({
success: false,
error: 'Error hashing password'
})
} else {
// Build query & insert into users table
const valuesStr = `(null, "${rBody.email}", "${rBody.firstName}", "${rBody.lastName}", "${hash}", null, 2)`
const queryString = `INSERT INTO users values${valuesStr}`
connection.query(queryString, (err, resp) => {
if (err) {
// Error inserting into users table
resolve({
success: false,
error: err
})
} else {
// User succesfully created
resolve({
success: true,
message: 'User succesfully created',
id: resp.insertId
})
}
})
}
})
})
}

Edit your query to insert into the table does not seem to follow the standard syntaxis. Try
const queryString = `INSERT INTO users(name of your columns) VALUES(${valuesStr}`)

Related

SQL Query not Giving a Result

I am trying to login my user and i need to search whether the user exists in the db or not. My db is ClearDB using MySQL on Heroku. I am using node.js. This is my code:
if (req.body.isAdmin === 1) {
connection.query(
`SELECT * FROM admin WHERE username='${req.body.username}' AND password='${req.body.password}'`,
function (err, rows) {
if (!err) {
console.log(rows);
res.status(201).json({
success: true,
message: "Admin Logged In!",
});
} else {
res
.status(404)
.json({ success: false, message: "Admin Not Found!" });
}
}
);
} else {
connection.query(
`SELECT * FROM guard WHERE username='${req.body.username}' AND password='${req.body.password}'`,
function (err, rows) {
if (!err) {
console.log(rows);
res.status(201).json({
success: true,
message: "Guard Logged In!",
});
} else {
res
.status(404)
.json({ success: false, message: "Guard Not Found!" });
}
}
);
}
} catch (error) {
res.status(500);
throw new Error(error);
}
In the above code, i first check whether the user is an admin or not, then i execute the respective query. The db connects properly i.e., there is no issue with the db connection.
The issue is that there is no output for any of the queries i.e., rows variable is empty. Even if the data is false and doesn't match the data available, it doesn't give an error and also doesn't give an output. I have double-checked the connection and the query and they seem fine. I don't get where the issue is. Please help!

Node Api rest - change database dynamically|

Is it possible to change the pool config database?
I have a rest API with node/express, and I have multiple databases.
So I need that when a user.company login in my frontend, the API rest, choose the database that user should use.
My configuration file for the bank is this .env
JWT_KEY=XXXXXXX
POOL1_USER=root
POOL1_PASSWORD=xxxxxx
POOL1_DATABASE=data1
POOL1_HOST=host.domain.com
POOL1_PORT=3306
Meu arquivo db.js é este:
const mysql = require("mysql");
const pool1 = mysql.createPool({
connectionLimit: 10,
user: process.env.POOL1_USER,
password: process.env.POOL1_PASSWORD,
database: process.env.POOL1_DATABASE,
host: process.env.POOL1_HOST,
port: process.env.POOL1_PORT,
});
module.exports = { pool1 };
Is this my controllers.js file?
const mysql = require("../db").pool1;
exports.adminGroup = (req, res, next) => {
mysql.getConnection((error, conn) => {
if (error) {
return res.status(500).send({ error: error });
}
conn.query(
"INSERT INTO adminGroup SET ?",
[req.body],
(error, results) => {
conn.release();
if (error) {
return res.status(500).send({ error: error });
}
response = {
mensagem: "Group add",
grupoCriado: {
id: results.insertId,
grupo: req.body.group,
},
};
return res.status(201).send(response);
}
);
});
};
I need to dynamically change the database, as I have the same frontend for the same rest API, but I have multiple databases that can even be on different hosts.
It may be that what I'm trying to implement is not possible, so does anyone have any different suggestions?
Before you use the query to select a table from a database, you need to switch the database, use this query to achieve that.
con.query("USE your_db_name", function (err, result, fields) {
if (err) throw err;
console.log(result);
});
then after it use the query that you want like this
const mysql = require("../db").pool1;
exports.adminGroup = (req, res, next) => {
mysql.getConnection((error, conn) => {
if (error) {
return res.status(500).send({ error: error });
}
con.query("USE your_db_name", function (err, result, fields) {
if (err) throw err;
console.log(result);
});
conn.query(
"INSERT INTO adminGroup SET ?",
[req.body],
(error, results) => {
conn.release();
if (error) {
return res.status(500).send({ error: error });
}
response = {
mensagem: "Group add",
grupoCriado: {
id: results.insertId,
grupo: req.body.group,
},
};
return res.status(201).send(response);
}
);
});
};

Express.js: Reponse in catch of try/catch is never sent

I'm trying to implement a basic user registration flow using Express.js and mySQL. This is the code I have at the moment (stripped for brevity):
register(app, db) {
app.post('/register', (req, res) => {
let email = req.body.email
let password = req.body.password
try {
// add the user to the database
var q_params = [email, bcrypt.hashSync(password, 9)]
db.query("INSERT INTO users VALUES (?, ?)", q_params, (err) => {
if (err) {
throw err
}
})
} catch (err) {
// respond with an error if one is encountered
res.json({
success: false,
msg: err
})
return
}
// respond with success if everything else goes ok
res.json({
success: true,
email: email
})
});
}
The problem is that no matter the outcome of the code in the try block, I am always getting success: true. How come the error response is never triggered? Is there a better way to be handling this scenario?
I'm assuming the issue is that the nothing is waiting for the db.query() function to finish executing. It's not async and not awaiting that function to resolve. So the last res.json({}) gets hit right away.
I would try to rewrite the code to either use promises or to use that callback function passed to .query(), maybe something like this:
app.post('/register', (req, res) => {
let email = req.body.email
let password = req.body.password
// add the user to the database
var q_params = [email, bcrypt.hashSync(password, 9)]
db.query("INSERT INTO users VALUES (?, ?)", q_params, (err) => {
if (err) {
return res.json({
success: false,
msg: err
});
}
res.json({
success: true,
email: email
});
});
});

User entries not updating in database

I am using postman to send a request and I see Success message but in the database, it's not updated at all.
PostMAN request
database Snap shot
update services object: from this file I have used a database query to insert data in the database and set callBack funtion
const pool = require('../../config/database')
module.exports = {
updateUser: (data, callBack) => {
pool.query(
`UPDATE users SET firstName=?,email=?,password=?,lastName=?,phoneNumber=?, sex=? WHERE id=?`, [
data.firstName,
data.email,
data.password,
data.lastName,
data.phoneNumber,
data.sex,
data.id
], (error, results, fields) => {
if (error) {
return callBack(error)
}
return callBack(null, results)
}
)
}
}
update user controller here I have added a controller to update the user details which receive the data from update user services.
const {
create,
getUserbyID,
getUsers,
updateUser,
deleteUser,
getUserByEmail
} = require('./userService')
const {genSaltSync, hashSync, compareSync} = require('bcrypt')
const { sign } = require('jsonwebtoken')
module.exports ={
updateUser: (req, res) => {
const body = req.body;
const salt = genSaltSync(10);
body.password = hashSync(body.password, salt);
updateUser(body, (err, results) => {
if (err) {
console.log(err)
return false;
} // added
console.log("this is the body: "+JSON.stringify(req.body))
console.log("this is the results: "+ JSON.stringify(results))
if (!results) {
return res.json({
success:0,
message: "failed to update user"
})
}
return res.json({
success: 1,
message: "Updated Sucessfully"
})
})
},
}
router.js
router.patch('/update',checkToken, updateUser)
ADDED console.log
this is the body: {"Id":15,"firstName":"joey","email":"joey.chandler357#gmail.com","password":"$2b$10$ZBnRppSKAfQ1TrzGvs/wqOrVx/shb6ESJ7emXnC7IlWRN3VUGgfK2","lastName":"chandler","phoneNumber":"9860316634","sex":"Male"}
this is the results: {"fieldCount":0,"affectedRows":0,"insertId":0,"serverStatus":2,"warningCount":0,"message":"","protocol41":true,"changedRows":0}
I can see your console.log message
this is the results: {"fieldCount":0,"affectedRows":0,"insertId":0,"serverStatus":2,"warningCount":0,"message":"","protocol41":true,"changedRows":0}
Here you can notice affectedRows: 0 it means no row updated this happens when condition is not matched with any of the records. In postman you are passing "Id" I is in capital format but at the time of accessing this in service you are using "data.id" id is small latter so this is creating problem
we can handle this
instead of
if (!results) {
return res.json({
success:0,
message: "failed to update user"
})
}
use
if (!results.affectedRows) {
return res.json({
success:0,
message: "failed to update user"
})
}
this will be much better then previous check
I think you need to use an "insert" to add the db record. It's using an update... so it's looking for a pre-existing record.
Try two things:
wrap “users” in quotes on your update query. I’ve seen this w Postgres where some words are reserved in raw queries.
Examine the database response from your update. See what is console logged.

AWS lambda post mysql duplicate key but no error, why?

In mysql table i have created, I set autoincrement and unique value for the primary key. It is
I ran the following code multiple times. it is suppose to show error most of the time due to repetitive keys entered, however, there was no error.
exports.handler = async (event) => {
var mysql = require('mysql');
// TODO implement
var connection = mysql.createConnection({
host : '-',
user : '-',
password : '-',
database : '-'
});
const sql = `INSERT INTO forms VALUES(20,2,4,4,5,6,7,8,9,10,11);`;
connection.query(sql, (err, res) => {
if (err) {
throw err
}
})
const wait = () => {
setTimeout(()=>console.log('timeout'),2000)
}
await wait();
await console.log(sql)
const response = {
statusCode: 200,
body: JSON.stringify('Hello from Lambda!'),
};
return response;
};
It is suppose to show error as below
But it shows no error most of the time.Why?