Mysql dynamic query in node.js - mysql

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

Related

get request with multiple parameters mySQL using node js

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

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.

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

node.js + mysql Query from url

I am new to this node.js. I am using mysql in my node.js. From the url i am constructing sql query. With 1 parameter its working fine.
The URL:
http://ipaddress:3002/users/Kappalur
By using the following code i extracted the Kappalur and its working fine:
app.get('/users/:level', function (req, res) {
connection.query("select * from levels where level4= '"+req.params.level+"'", function(err, rows, fields) {
res.writeHead(200, { 'Content-Type': 'application/json'});
res.end(JSON.stringify(rows,null,"\n"));
Now my requirement is i want to make "level4" to be dynamic..
Consider now the url be:
http://ipaddress:3002/users/level4/Kappalur
Now how can i change the above code to get the 2 parameters from url. Help me to solve this..Thanks in advance.
As I understood you are using express framework for node.js.
To retrieve multiple URL parameters use just the same pattern as that you have used in your post's code snippet:
app.get('/users/:level/:name', function (req, res) {
var level = req.params.level;
var name = req.params.name;