I am trying to create a post route that will delete a user's data from several tables. I checked in mySQL workbench that the database user has this privilege. However when I click delete on the frontend, the queries appear to run but the rows do not get deleted. Can you someone please tell me where I am going wrong?
app.post('/disposal', redirectLogin, async(req, res) => {
const user = res.locals;
userStmt = `DELETE FROM users WHERE user_name ='${user.user_name}'`;
cashStmt = `DELETE FROM CASH WHERE user_name ='${user.user_name}'`;
tradesStmt = `DELETE FROM trades WHERE user_name ='${user.user_name}'`;
holdingsStmt = `DELETE FROM trades WHERE user_name ='${user.user_name}'`;
await connection.query(userStmt, (err, results) => {
if (err) throw err;
console.log(results);
connection.query(holdingsStmt, (err, results) => {
if (err) throw err;
console.log(results);
connection.query(cashStmt, (err, results) => {
if (err) throw err;
console.log(results);
});
connection.query(tradesStmt, (err, results) => {
if (err) throw err;
console.log(results);
});
});
});
req.session.destroy(err => {
if (err) {
return res.redirect("/dashboard");
}
res.clearCookie(SESS_NAME);
res.send("Ninja disposed!");
})
})
I needed to change user = res.locals to { user } = res.locals as it the former was coming back 'undefined' as it was not properly extracting.
You don't need to nest the calls if you are using async/await.
As the res.locals is an object which contains the user property, you have to get the user property.
You could get it by using Object destructuring syntax.
Try this.
app.post('/disposal', redirectLogin, async (req, res) => {
const { user } = res.locals;
userStmt = `DELETE FROM users WHERE user_name ='${user.user_name}'`;
cashStmt = `DELETE FROM CASH WHERE user_name ='${user.user_name}'`;
tradesStmt = `DELETE FROM trades WHERE user_name ='${user.user_name}'`;
holdingsStmt = `DELETE FROM trades WHERE user_name ='${user.user_name}'`;
try {
let results = await connection.query(userStmt);
console.log(results);
let holdinResult = await connection.query(holdingsStmt);
console.log(holdinResult);
let cashResult = await connection.query(cashStmt);
console.log(cashResult);
let tradesResult = await connection.query(tradesStmt);
console.log(tradesResult);
} catch (error) {
throw error
}
req.session.destroy(err => {
if (err) {
return res.redirect("/dashboard");
}
res.clearCookie(SESS_NAME);
res.send("Ninja disposed!");
})
})
Related
I have a post api which i want to validate data before inserting it into data base .
I want to check if the customerCode from the body exists in database or not .
this is my code but it always returns " Cannot read properties of undefined (reading '0')"
app.post('/CreateCustomer', (req, res) => {
pool.getConnection((err, connection) => {
if (err) throw err
const params = req.body
connection.query('SELECT CustomerCode FROM Customers WHERE CustomerCode = ?', params.CustomerCode, (err, rows) => {
// connection.release() // return the connection to pool
if (rows[0] == undefined) {
connection.query('INSERT INTO Customers SET ?', params, (err, rows) => {
connection.release() // return the connection to pool
if (!err) {
res.send(`Customers with the record ID has been added.`)
} else {
console.log(err)
}
console.log('The data from beer table are:11 \n', rows)
})
} else {
res.send("Csutomer Code Already taken!")
}
})
})
})
When I'm trying to send a POST request using Postman, it gives me this error: "Cannot read properties of undefined (reading 'product_title')"
app.post("/product", async (req, res, next) => {
let product = {
product_title: req.body.product_title,
product_price: req.body.product_price,
product_type: req.body.product_type,
product_brand: req.body.product_brand,
};
let sql = `INSERT INTO products SET ?`;
await db.query(sql, product, (err, result) => {
if (err) {
throw err;
}
console.log(result);
});
res.send("Added");
});
use ? keyword
app.post("/product", async (req, res, next) => {
let product = {
product_title: req.body?.product_title,
product_price: req.body?.product_price,
product_type: req.body?.product_type,
product_brand: req.body?.product_brand,
};
let sql = `INSERT INTO products SET ?`;
await db.query(sql, product, (err, result) => {
if (err) {
throw err;
}
console.log(result);
});
res.send("Added");
});
app.post('/addUsername', (req, res)=> {
const username = req.body.username;
db.query("SELECT * FROM userbase WHERE username = ?"), [username], (err, result)
if(result == username)
{
db.query("INSERT INTO userbase (username) VALUE (?)", [], (err, result)=> {
console.log(err);
})
}
else{
db.query("INSERT INTO userbase (username) VALUE (?)", [username], (err, result)=>
{
console.log(err);
})
}
})
I was trying to make it so if the username exist it would not send data to the database. but I dont think I structured this correctly. Basically this database is a big list full of usernames.
Hey I would like to send back an image downloaded from s3 and data from MySQL database but i'm not sure if its even possible and if it is, how to do it.
Any help is welcome thanks!
app.get('/api/users/:id', (req, res) => {
var id = req.params.id;
pool.getConnection((err, connection) => {
if (err) throw err
console.log('connected as id ' + connection.threadId)
connection.query(`SELECT username, picture, DATE_FORMAT(creation_date, "%d %M %Y") as creation_date from users where idusers = ${id}`, (err, rows) => {
connection.release() // return the connection to pool
if (!err) {
const readStream = getFileStream(rows[0].picture);
readStream.pipe(res);
res.send(rows[0])
} else {
console.log(err)
}
})
});
})
I am having trouble with querying whole or parts of the column in a single row.
I am creating a form that can both create (post) and edit(put) data into the form.
I managed to make the function post and delete work, but put(edit) always return a sql syntax error. The syntax works fine when simulating on phpmyadmin.
What is correct way of doing this? Thanks a lot.
exports.putProduct = router.put("/api/product/update/:id", (req, res) => {
const putData = req.body;
const idToPutData = req.params.id;
mySQL.query(
// "UPDATE `product` SET `category`=?, `productname`=?, `os`=?, `model`=?, `serialnumber`=?, `price`=?, `equipment_condition`=?, `detail`=?, `image`=? WHERE id=?", [putData, idToPutData],
"UPDATE `product` SET ? WHERE id=?", [putData, idToPutData],
(err, results, fields) => {
if (err) console.log(err);
}
);
});
exports.postProduct = router.post("/api/product/new", (req, res) => {
const postData = req.body;
mySQL.query(
"INSERT INTO `product` SET ?", postData,
(err, results, fields) => {
if (err) console.log(err);
res.end(JSON.stringify(results));
}
);
});
exports.deleteProduct = router.delete("/api/product/delete/:id", (req, res) => {
const conDeleteData = { id: req.params.id }
const idToDelete = req.params.id
mySQL.query(
"DELETE FROM `product` WHERE id=?", [idToDelete, conDeleteData],
(err, results, fields) => {
if (err) console.log(err);
res.end(JSON.stringify(results));
}
);
});
This is the correct way to perform a MySQL query update using Nodejs
exports.putProduct = router.put("/api/product/update/:id", (req, res) => {
const putData = req.body;
const idToPutData = req.params.id;
mySQL.query(
"UPDATE `product` SET `category`=?, `productname`=?, `os`=?, `model`=?, `serialnumber`=?, `price`=?, `equipment_condition`=?, `detail`=?, `image`=? WHERE id=?",
[putData.category, putData.productname, putData.os, putData.model, putData.serialnumber, putData.price, putData.equipment_condition, putData.detail, putData.image, idToPutData],
(err, results, fields) => {
if (err) console.log(err);
res.end(JSON.stringify(results));
}
);
});