requests not going through in nodejs and mysql - mysql

I have this code where I am trying to receive data from the user and it should be inserted into the db directly without any module just a controller, can someone tell me how can I do that, I know we can get the user data in the req.body, but I don't know how to send it back to the controller here is the
P.S user will be sending around 10 or more fields that will be inserted
here is the code
controller
sql.query(`INSERT INTO Admin (LoginID,Password,Preference,Name,Last Name) values ? ` , (err, result)=> {
if (err) {
console.error('Something bad happened: ' + err);
return res.status(500);
}
console.log('Response from controller', result);
res.json(result);
});
}
module.exports = {test}
and this is the router page
Router
router.post('/CreateOrganizer',(req,res)=>{
organizer.test
})

This is how you should proceed:
const con = mysql.createConnection({
host: "localhost",
user: "yourusername",
password: "yourpassword",
database: "mydb"
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
});
app.post('',(req, res, next) => {
const user = req.body;
// use the same key in the query that you are getting from body.
const sql = "INSERT INTO Admin (LoginID,Password,Preference,Name,Last Name)
VALUES ('user.LoginID', 'user.Password', 'user.Preference', 'user.Name''user.LastName')";
con.query(sql, function (err, result) {
if (err) {
console.error('Something bad happened: ' + err);
return res.status(500);
}
console.log("1 record inserted");
});
})
There are several tutorials available online that can help you to achieve the same.

Related

How to pass multiple parameters for promise function in Nodejs connected with MYSQL server?

let mysql = require('mysql');
let connection = mysql.createConnection({
host: 'localhost',
user: 'priyanka',
password: '1234',
database: 'todoapp'
});
connection.connect(function(err) {
if (err) {
return console.error('error: ' + err.message);
}
console.log('Connected to the MySQL server.');
});
// promise function
query = `select device from user_table limit 34`;
sql = function(device){
return new Promise(function(resolve,reject)
{
connection.query(query, (error, results) => {
if (error) {
reject( console.error(error.message));
}
resolve(console.log(results));
});
})
}
sql('device').then(function(rows) {
}).catch((err) => setImmediate(() => { throw err; }));
connection.end();
sql('device') -> inside sql call , can i only place comma separated field values to get rows from user_table or is there any other way to pass multiple columns ?

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 Express MySQL , can not get all users

I can't get all users, but if write manually it works.
class User {
static getAll(result) {
let sql = `SELECT * FROM users`;
sql.query(sql, (err, res) => {
if (err) {
console.log("error: ", err);
result(null, err);
return;
}
console.log("users: ", res);
result(null, res);
});
}
}
exports.findAll = (req, res) => {
User.getAll = (err, data) => {
if (err) return res.status(500).send({ message: err.message || "Some error occurred while retrieving users." });
res.send(data);
}
}
query() is a method of a mysql connection, you are using it as a string method:
let sql = 'SELECT * FROM users';
sql.query()
You should first create the connection with your database, and then use that connection object to make your queries, something like this:
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "yourusername",
password: "yourpassword",
database: "mydb"
});
con.connect(function(err) {
if (err) throw err;
con.query("SELECT * FROM users", function (err, result, fields) {
if (err) throw err;
console.log(result);
});
});

Terminating a callback in nodejs

I am very new to nodejs. I am using mysql node module. This is how I use it:
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'sample'
});
connection.connect(function (err) {
if (!err) {
console.log("Database is connected ... \n\n");
} else {
console.log("Error connecting database ... \n\n");
}
});
var post = {PersonID: 1, Name: 'Prachi', City: 'Blore'};
var query = connection.query('INSERT INTO Persons SET ?', post, function(error, result) {
if (error) {
console.log(error.message);
} else {
console.log('success');
}
});
console.log(query.sql);
This node code works functionally. As in, it adds data to the table. But it doesn't terminate. What is the mistake which I am making?
Take a closer look at the official documentation, you have to close the connection :
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'me',
password : 'secret'
});
connection.connect();
connection.query('SELECT 1 + 1 AS solution', function(err, rows, fields) {
if (err) throw err;
console.log('The solution is: ', rows[0].solution);
});
connection.end();
Use connection.end() to close the connection
var query = connection.query('INSERT INTO Persons SET ?', post, function(error, result) {
connection.end();
if (error) {
console.log(error.message);
} else {
console.log('success');
}
});

Nodejs - Express - Mysql: render view after post

I am using express to insert/list some records from a mysql db. Everything works fine (insert/select) but how do I render the list function after insert was completed? Do I have to re-invoke the select statement?
var mysql = require('mysql');
exports.create = function(req, res) {
var connection = mysql.createConnection({user: 'root', password: 'password', database: 'test'});
connection.query('INSERT INTO wall (message) VALUES ("' + req.body.message + '")', function(err, result) {
if (err)
throw err
// is this correct? <===
connection.query('SELECT * FROM wall', function(err, rows) {
if (err)
throw err
if (rows)
res.render('wall', {title: 'Wall', data: rows});
});
// end
connection.end();
});
};
exports.list = function(req, res) {
var connection = mysql.createConnection({user: 'root', password: 'password', database: 'test'});
connection.query('SELECT * FROM wall', function(err, rows) {
if (err)
throw err
if (rows)
res.render('wall', {title: 'Wall', data: rows});
});
connection.end();
};
Yes, you do have to SELECT again, and your code is generally correct. I would refactor the common part between list and the part you're asking about, I would not list users and passwords in source files, and make other minor modifications, but generally it's correct.
I read the docs more carefully and i found
res.redirect();
so for my example, it works just fine to do
res.redirect('/wall');
to make a GET request to /wall route. The data will come as this route fetching the list of messages. Thats ok for me.