Pass the dropdown selected value to NodeJS for querying database - mysql

i have created one dropdown that passes data to NodeJS through axios post i can see that in console log of nodejs Post but cant able to use the value outside the post function
i want to use the value to querying the database
my nodejs code:
app.post('/getmodel', (req, res) => {
var model = req.body.model;
console.log(model);
//It shows model value here but can't able to use outside
});
app.get('/model', (req,res)=>{
let model = req.body.model;
let sql ="select * from new_schema.model_list,new_schema.images where model_name= " + mysql.escape(model)
db.query(sql,model, (err,results) =>{
if(err){
throw err
}
console.log(results)
res.send(results);
})
})
my react code works fine as i can able to see the selected value in nodejs console below
these are the selected value from my dropdown that shows in my nodejs console. but in cant use it by req.body like that please help me

You can try like this
app.post('/getmodel', (req, res) => {
var model = req.body.model;
console.log(model);
//It shows model value here and you can able to use in the query
let sql = "select * from new_schema.model_list,new_schema.images where model_name= " + mysql.escape(model)
db.query(sql, model, (err, results) => {
if (err) {
throw err
}
console.log(results)
res.send(results);
})
});

Related

dynamic link not working when pulling info from mysql database

So my goal is to pull info from the database when a user logs in to have it in the URL for when they are logged into their account, I can get the information I am looking for but when I go to log in to the account I am getting this error
Cannot GET /main-component[object%20Object]
and this in the URL
http://localhost:3000/main-component[object%20Object]
I have tried different variations of writing my code and no matter what whenever I go to put the info into the redirect link I just get an error. I am connected to the database and getting data just not able to redirect to the next place on the website.I am new to nodejs so I'm not exactly sure what to do from this point. Thanks for the help and heres my code
let str
let testi
function output(rows){
str = rows
console.log(str)
return str
}
app.post('/login-validate', (req, res) =>{
// let user = userInfo(req.body.email, req.body.password)
// console.log(user)
testi = pool.query('SELECT * FROM users WHERE email=? AND password=?',[req.body.email, req.body.password], (err, res) =>{
if(err){
console.log(err)
}
output(res[0].first_name)
})
res.redirect('/main-component' + testi)
})
app.get('/main-component/:id', (req,res) =>{
res.render('calanderView')
})

How to get a freshly Inserted Id with reactjs (Axios)?

I am trying to retrieve the Id value of a freshly Inserted row in Mysql with react Axios.
Here Is my code In node.js
app.post('/createProject', (req,res) => {
const projectName = req.body.projectName;
const tjm = req.body.tjm;
const status = req.body.status;
db.query("INSERT INTO projects (projectName, tjm, status) VALUES (?,?,?)",
[projectName, tjm, status],
(err, result) => {
if (err) {
console.log(err);
} else {
res.send("Values Inserted");
res.send(result.insertId);
console.log(result.insertId);
}
}
);
});
I try to get the insertId with a UseState hook;to use It in another Post request and store It in another table.
The post request In react:
const [id, setId] = useState();
const addProject = () => {
Axios.post("http://localhost:3001/createProject", {
projectName: projectName,
tjm: tjm,
status: "Inachevé"//Uncomplete,
}).then((res) => {
console.log("success");
setId(res.data);
});
};
I try console.log(id) but I get undefined in the console.
The post request to get the Inserted Id of the project:
const addWork = () => {
Axios.post("http://localhost:3001/createWork", {
EmpID: id_e,//I get that Id from a drop-down list
PrID: id_p,// the Id of the Inserted project who I can't get
}).then(() => {
console.log("success");
});
};
When I fill my Inputs In the frontend and send the the data (prjectName,tjm & status),the data is stored normally and the insertId consoled In the backend but I can't get it in my client side.
How I can access to insertId in the frontend and store It In another table at the same time when creating a new Project?
note: I think that I should use async/await to make addWork function wait until addProject execute but the probleme Is how to get the insertId In the frontend.
You should not use res.send() twice. You would probably want to send json, which works like the following: res.status(200).json({message: "Message",data: lastInsertedID}).
You would then need to make sure to correctly access the id in the frontend. Therefore you can print the whole json response object from on the console and make your way through the json object until you reach the id.

API delete call for row from MySQL DB not work

I'd like to create api call from back-end for DELETE query from mysql DB but when execute it in browser get error
'Cannot GET ...'
I pass into the route id of row which had got from DB
At back-end the code is:
app.delete('/products/delete/:id*?', function(req, res) =>{
let { id } = req.query;
let DELETE_PRODUCT_FROM_DB = `DELETE FROM my_db.products WHERE my_db.id= '${req.query}'`;
console.log("id: ", req.query);
// delete a row with id = req.query
connection.query(DELETE_PRODUCT_FROM_DB, (error, results, fields) => {
if (error) return console.error(error.message);
res.status(200).send(results);
console.log("Deleted Row(s):", results.affectedRows);
});
});
But finally this call not works and row not deleted
let DELETE_PRODUCT_FROM_DB = `DELETE FROM my_db.products WHERE my_db.id= '${req.query.id}'`;
console.log("id: ", req.query.id);
Try using this.
fetch(url, {
method: 'delete'
}).then(response => response.json());
Try running this in your browser console. It should work.
Most likely you're making a GET call to a DELETE resource.
Please read Express 4.x. Can you share the code you're using to make DELETE request from browser?
I did some changes and now running version of the code looks like
app.delete('/products/delete/:id', (req, res) => {
let { id } = req.params ;
let DELETE_PRODUCT_FROM_DB = `DELETE FROM my_DB.products WHERE id= '${id}'`;
console.log('id: ', req.params);
// delete a row with id = req.params
connection.query(DELETE_PRODUCT_FROM_DB, (error, results, fields) => {
if (error) return console.error(error.message);
res.status(200).send(results);
console.log('Deleted Row(s):', results.affectedRows);
});
});
Also, I figured out that changes from req.query on req.params helped to get id from the link as a parameter

Node Express MySQL multiple routing

I want to make an route with multiple parameters using Node Express MySQL. Is it possible to do this with traditional url parameters like: page?id=2&user=10
Here is a simple query, but the only way of doing it so far is like this: page/2/10
app.get("/get-page/:id/:user", function (req, res) {
let sql = "SELECT * FROM table WHERE id= '${req.params.id}' AND userid= '${req.params.user}'`;";
let query = db.query(sql, (err, results) => {
if (err) throw err;
res.send(results);
});
});
This is just an example.
The reason I would like the traditional way is because, with the "slash" method the parameters always have to come in the correct order, or did I miss something?
Perhaps use the query property of the request to access the query string, as in req.query.id:
app.get("/get-page", function (req, res) {
console.log('ID: ' + req.query.id)
});

how do I access the result(object) of a get request using express?

Here is my get request made to a mysql table
app.get('/', (req, res) => {
let sql = 'SELECT * from emarttesttable WHERE id = 229';
let query = db.query(sql, (err, results) => {
if(err){console.log(err);}
else{
console.log(results);
}
});
res.render('index');
});
As it stands, this function allows me to grab the information I want from the table and I can read the results via console.log. However, I'm unable to access results on my index.ejs page.
How do I access results(which is an object that contains the stuff I want) in my index.ejs file? Whenever I try to access results, it says that results in undefined. How do I make sure that the object that is created as a result of the call to the table is able to be used/accessed on a different page. For the time being, I would just like to create a simple table that has the keys in one column and the values in a second column.
You need to modify your code as below. The reason is db.query is an async operation and you are trying to render before the async request completed. Also, to be able to reach the result at your template engine, you need to pass the results to the render. (index.ejs)
app.get('/', (req, res) => {
let sql = 'SELECT * from emarttesttable WHERE id = 229';
let query = db.query(sql, (err, results) => {
if(err){console.log(err);}
else{
res.render('index', results);
console.log(results);
}
});