get request with multiple parameters mySQL using node js - mysql

I'm writing REST API in node js.
In my database I have two FK (user_A, user_B)
user_A - int (FK)
user_B - int (FK)
create_date - date
My GET request:
http://localhost:3000/chats?useridA=1&useridB=1
And my code:
app.get('/chats/:useridA/:useridB', (req, res) => {
mysqlConnection.query("SELECT * FROM Chats WHERE user_A_app_id = ? AND user_B_app_id = ?",
[req.params.useridA, req.params.useridB], (err, rows) => {
try
{
res.send(rows);
}
catch (err)
{
console.log(err.message);
}
})
});
The output in postman is the entire table and not the specific row.
What's the problem in my code or in my get request?
In general the "WHERE" statement in my code is not working with more then one parameters.
This is the "create table Chats" in my sql file for my database

your GET request is using query parameters:
http://localhost:3000/chats?useridA=1&useridB=1
So to use it inside your nodejs code, you can access those parameters us:
req.query.useridA
req.query.useridB
So the request should be like this:
app.get('/chats/:useridA/:useridB', (req, res) => {
mysqlConnection.query('SELECT * FROM Chats WHERE user_A_app_id =' +req.param("useridA")+ 'AND user_B_app_id =' +req.param("useridB")', (err, rows) => {
try {
res.send(rows);
}
catch (err) {
console.log(err.message);
}
})
});
or you just call get request using url parameters
http://localhost:3000/chats/:useridA/:useridB
http://localhost:3000/chats/1/1

Related

Pass the dropdown selected value to NodeJS for querying database

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

Why is my Axios get request getting the entire array instead row associated with the param I pass in?

I am using Axios requests to retrieve data from MySQL with an express server in between.
I have an API route of 'http://localhost:3001/find' which displays the following json when accessed:
[{"id":1,"title":"book title 1","author":"book author 1",},
{"id":2,"title":"book title 2","author":"book author 2"}]
I am trying to retrieve the singular row with the id of 1, so am doing this get request:
const searchMe = () => {
Axios.get('http://localhost:3001/find', {
params: {
"id": "1"
}
})
.then(function (response) {
console.log(response);
})
}
However when I console log the response I get both rows instead of just the one. Is is possible the param isn't getting read properly or something?
EDIT: Here is the code in my express server for handling the 'find' request:
app.get('/find', (req, res)=>{
const sqlInsert = "SELECT * FROM songs;"
db.query(sqlInsert, (err, result)=> {
res.send(result)
// console.log(result);
})
});
I know it definitely works because it is returning the data.

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

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

Mysql dynamic query in node.js

I am new to this node.js concepts.What i have tried is updating a database and retreiving datas from database(working fine).On further step i returned the output(from database) into an "JSON" format(working fine)..Now my requirement is to have a dynamic query..
Consider:
The following url:
http://xxx.xxx.xx.x:3002/users will retrieve all datas from users table and return in json format
But what i want is:
http://xxx.xxx.xx.x:3002/users=abcdef so the datas for that particular user should be returned in json format.
My code:
app.get('/users', function (req, res) {
connection.query('select * from nodejs where', function(err, rows, fields) {
res.writeHead(200, { 'Content-Type': 'application/json'});
res.end(JSON.stringify(rows));
//res.render('users', {users: docs});
});
});
So how can i modify the above code to retrieve only for specific users details..Help me to solve this..Thanks in advance..
Create a new route in your application. You can specify parameters in your URL as
http://xxx.xxx.xx.x:3002/users/fname1
Here fname1 is user Id and you can add the following code to get the parameter from url
req.params.fname
Here the fname is got the name from the route that defined in your application as:
app.get('/users/:fname', function (req, res) {
connection.query("select * from nodejs where fname= '"+req.params.fname+"'", function(err, rows, fields) {
res.writeHead(200, { 'Content-Type': 'application/json'});
res.end(JSON.stringify(rows));
//res.render('users', {users: docs});
});
});
Use url/:nameOfParameter to specify the name for values in url