Error: Cannot destructure property 'name' of 'req.body' as it is undefined - mysql

I'm learning how to work with databases and I ran into the following problem that I can't solve:
I'm trying to change the data in the table, but I get an error every time
That's my Node.Js code:
app.post('/db/:userId', async (req, res)=> {
const { userId } = req.params
try {
const conn = mysql.createConnection({
host: 'localhost',
user: 'root',
database: 'testdb',
password: ''
})
conn.connect( err=> {
if (err) {
console.log(err)
return err
} else {
console.log('DATABASE ----- CONNECTED SUCCESSFULLY')
}
})
const { name, scnmb, login, password, isLogged } = req.body;
let create = `UPDATE user_info SET name = '${name}', scnmb = '${scnmb}', login = '${login}', password = ${password}, is_logged = '${isLogged}' WHERE user_info.id = ${userId};`
conn.query(create, async (err, result) => {
if (err) {
console.log(err);
res.status(500).send("Error creating user");
} else {
res.json(result);
}
});
conn.end(err=> {
if (err) {
console.log(err)
return err
} else {
console.log('DATABASE ----- DISCONNECTED SUCCESSFULLY')
}
})
} catch (e) {
console.log(e)
res.statusCode = 500
res.json({ errcode: 500, errmsg: 'DataBase error', ...e})
}
})
That's my request body(Im using Postman):
{
"name": "Nikita",
"scnmb": 5,
"login": "+888",
"password": 0,
"isLogged": 1
}
And that's an error I get:
TypeError: Cannot destructure property 'name' of 'req.body' as it is undefined
I'm sure this problem is simple, but I just don't have any experience to solve it.
Can you help me?

Related

TypeError MySQL: Bind parameters must not contain undefined

So here is the controller's code which I am using to handle password generation process. There is a table called as passwordrecovery which has the following columns:-
id
uuid
email
isActive
Code
File: db.js
const mysql = require("mysql2");
const connectionPool = mysql.createPool({
user: "root",
database: "expensetracker",
host: "localhost",
password: process.env.MYSQL_PASSWORD,
});
module.exports = connectionPool;
File- users.js
const path = require("path");
const db = require("../database/db");
exports.passwordGenerator = async (req, res, next) => {
var id = req.query.id;
console.log(id);
await db.execute(
"SELECT uuid, isActive FROM passwordrecovery WHERE id = ?",
[id],
(err, results) => {
if (err) {
console.log(err);
res.status(500).send("SERVER ERROR");
} else {
//console.log(results);
const response = results[0];
const isActive = parseInt(response.isActive);
if (isActive == 1) {
db.execute(
"UPDATE passwordrecovery SET uuid = ?, isActive = 0 WHERE id = ?",
[null, id],
(err, results) => {
if (err) {
console.log(err);
return res.status(500).send("SERVER ERROR");
} else {
console.log(results);
return res
.status(200)
.sendFile(
path.join(
__dirname,
"..",
"views",
"password-reset-form.html"
)
);
}
}
);
} else {
res.status(408).send("SESSION EXPIRED");
}
}
}
);
};
Error Message
undefined
TypeError: Bind parameters must not contain undefined. To pass SQL NULL specify JS null
at D:\Projects\Expense Tracker\Backend\node_modules\mysql2\lib\connection.js:659:17
at Array.forEach (<anonymous>)
at PoolConnection.execute (D:\Projects\Expense Tracker\Backend\node_modules\mysql2\lib\connection.js:651:22)
at D:\Projects\Expense Tracker\Backend\node_modules\mysql2\lib\pool.js:172:14
at D:\Projects\Expense Tracker\Backend\node_modules\mysql2\lib\pool.js:45:37
at processTicksAndRejections (node:internal/process/task_queues:78:11)
I was expecting that this express js server would return that html(password-reset-form.html) file which it does, here is response from server but it also console logs this error message. I don't know what to, tried my best to resolve myself, read some blogs, googled some stuff but still could not solve this error!

Can't get status

I am making register/login page using nodejs but when it comes to the step it returns json when accessing the database as well as when creating a new database
here is my code
register.js
const bcrypt = require("bcryptjs");
const User = require("../model/user");
const register = async (req, res) => {
const {
username,
password: plainTextPassword,
password_confirmation: someOtherPlaintextPassword,
tel_or_email,
} = req.body;
if (!username || typeof username !== "string") {
return res.json({ status: "error", error: "Invalid username" });
}
if (!plainTextPassword || typeof someOtherPlaintextPassword !== "string") {
return res.json({ status: "error", error: "Invalid password" });
}
User.findOne({ Email: tel_or_email }, async (error, user) => {
if (error) throw error;
if (user) {
console.log(user);
return res.json({
status: "ok",
success: "email is already in use, please enter another email",
});
} else {
const password = await bcrypt.hash(plainTextPassword, 10);
const password_confirmation = await bcrypt.hash(
someOtherPlaintextPassword,
10
);
const user = new User({
Name: username,
Email: tel_or_email,
Password: password,
});
user.save((error, result) => {
if (error) throw error;
console.log(result);
});
return res.json({ status: "ok", success: "user successfully created" });
}
});
};
module.exports = register;
status work in the first return ( return res.json({ status: 'error', error: 'Invalid username'}) )and the second( return res.json({ status: 'error', error: 'Invalid password'}) ) , remaining is not

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);
}
);
});
};

Node Js with mySQL return Null

I am trying to Skip the data if there is nothing return from the mySql Database
How can I achieve it?
Here is my code
const mysql = require('mysql2');
function dbconnection() {
const connection = mysql.createConnection({
host: '127.0.0.1',
user: 'root',
password: 'password',
database: 'DB'
});
var Data_export = dbconnection();
Data_export.query(sql, function (err, data, fields) {
if (err) throw err;
if (data !== Null) {
const jsonData = JSON.parse(JSON.stringify(data));
fastcsv
.write(jsonData, { headers: true })
.on("finish", function () {
console.log("Write to file.csv successfully!");
})
.pipe(ws);
} else { console.log("Nothing"); }
But it doesn't work
Any help would be greatly appreciated, thanks!
You must return something on your connection's function, and the code has some syntax issues.
It must work:
function dbconnection() {
const connection = mysql.createConnection({
host: '127.0.0.1',
user: 'root',
password: 'password',
database: 'DB'
});
return connection;
}
var Data_export = dbconnection();
Data_export.query(sql, function (err, data, fields) {
if (err) throw err;
if (data !== Null) {
const jsonData = JSON.parse(JSON.stringify(data));
fastcsv
.write(jsonData, { headers: true })
.on("finish", function () {
console.log("Write to file.csv successfully!");
})
.pipe(ws);
} else {
console.log("Nothing");
}
});
I found the solution
Because it is a return array from the mysql,
So instead of
if (data !== Null) {
const jsonData = JSON.parse(JSON.stringify(data));
fastcsv
.write(jsonData, { headers: true })
.on("finish", function () {
console.log("Write to file.csv successfully!");
})
.pipe(ws);}
I use this one
if (data.length !==0) {
const jsonData = JSON.parse(JSON.stringify(data));
//write duplication to CSV file
fastcsv
.write(jsonData, { headers: true })
.on("finish", function () {
console.log("Write to file.csv successfully!");
})
.pipe(was); }

how to use mysq transaction commit rollback in Lambda function using nodeJs

Hi i want to use Mysql's beginTransactio or transactio commit rollback functionality in my Lambda(Node) function.
I tried basic structure of mysql package but seems its not working in lambda
const mysql = require('mysql');
exports.handler = async (event) => {
const con = mysql.createConnection(
{
host: "host",
user: "user",
password: "*****",
database: "db"
}
);
con.beginTransaction(
function (err) {
con.query(
"query goes here",
function (err, status) {
if (err) {
con.rollback();
con.end();
return err;
} else {
con.commit();
con.end();
return true;
}
})
});
}
sorry for the delayed answer.
just needed to specify beginTransaction without callback
const mysql = require('mysql');
exports.handler = async (event) => {
const con = mysql.createConnection(
{
host: "host",
user: "user",
password: "*****",
database: "db"
}
);
con.beginTransaction(); //here i was declaring standard callback function with err parameter
con.query(
"query goes here",
function (err, status) {
if (err) {
con.rollback();
con.end();
return err;
} else {
con.commit();
con.end();
return true;
}
});
}