React.js + Express: how to run SQL requests implying several databases? - mysql

I am currently working on the API of a React.js project. I have no trouble running SQL requests with databases on MySql servers using Express as long as the SQL request only implies a single database.
My problem: I now have to run an SQL request which implies using data from several databases and I do not know how to do it.
What I currently do in my server.js file to run SQL on a single database:
...
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const mysql = require('mysql');
...
let sql = "";
...
// *************************
// CLIENT & DB CONFIGURATION
// *************************
const app = express();
app.use(bodyParser.json()); // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true
}));
var server = app.listen(3001, "127.0.0.1", function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
});
app.use(cors());
const connection = mysql.createConnection({
host : 'myhost.fr',
user : 'someone',
password : 'aZefdt%',
database : 'SuiviTruc',
multipleStatements : true
});
connection.connect(function(err) {
if (err) throw err
console.log('You are now connected with SuiviTruc database...')
});
// **************
// Request sample
// **************
app.get('/SelectAffaire_',(req, res) => {
let sql=`SELECT * FROM t_Affaire_;`
connection.query(sql, (error, result)=> {
if (error) throw error;
res.send(result);
})
})
Thanks for your help!

Related

Getting PROTOCOL_PACKETS_OUT_OF_ORDER in MySQL Node.js connection

I am an absolute newbie to Node.js. I am trying to create a MySQL database and connect it to a node.js server and build APIs.
Here's my db.config.js:
const mysql = require('mysql');
//local mysql db connection
const dbConn = mysql.createConnection({
host : '127.0.0.1',
user : 'root',
password : '',
database : 'node_mysql_crud_db'
});
dbConn.connect(function(err) {
if (err) throw err;
console.log("Database Connected!");
});
module.exports = dbConn;
And here's my server.js:
const express = require('express');
const bodyParser = require('body-parser');
// create express app
const app = express();
// Setup server port
const port = process.env.PORT || 3306;
// parse requests of content-type - application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }))
// parse requests of content-type - application/json
app.use(bodyParser.json())
// define a root route
app.get('/', (req, res) => {
res.send("Hello World");
});
// Require employee routes
const employeeRoutes = require('./src/routes/employee.routes')
// using as middleware
app.use('/api/v1/employees', employeeRoutes)
// listen for requests
app.listen(port, () => {
console.log(`Server is listening on port ${port}`);
});
When I run nodemon server, I get the following error:
/Users/mac/Flutter_Projects/NodeMysqlCrudApp/config/db.config.js:12
if (err) throw err;
^
Error: Packets out of order. Got: 80 Expected: 0
code: 'PROTOCOL_PACKETS_OUT_OF_ORDER',
fatal: true
I have added max_allowed_packet=500M in my.cnf file and yet I continue to receive the error.
How to resolve this issue?

Getting "Cannot GET /isFavorite" on my Node.js app hosted on DigitalOcean

Why am I getting the following error? I have a small Nodejs app hosted on DigitalOcean. I am getting the following error "Cannot GET /isFavorite" when I run the following post command in Postman: "http://octopus-app-s7q5v.ondigitalocean.app:8080/isFavorite" with body JSON parameters of:
{
"userid": "101",
"petid": "1"
}
The route I have for the app is an app.post("/isFavorite") and not an app.get. It is connected to a MySQL database which is also hosted on DigitalOcean. I have included a small version of the code for the app below. Why would I be getting this error? When I add an app.get("/") and return a response of "Hello" that works. It runs locally. I have configured all the environment variables in DigitalOcean settings. I have the "ca-certificate.crt" in the root of my Nodejs app. DigitalOcean app platform says it builds and deploys fine on the server.
Also, regarding the console.logs I have added to the code, where are they stored? I can see the one which starts the webserver and listens but not any of the others. The app is listening on port 8080 and has an IP address of 0.0.0.0.
const bodyParser = require("body-parser");
const querystring = require('querystring');
const router = express.Router();
const app = express();
app.use("/", router);
const mysql = require('mysql');
const fs = require('fs');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(express.json());
app.post("/isFavorite", (req, res) => {
try {
console.debug("isFavorite Start");
const conn = mysql.createConnection({
host: process.env.DBHOST,
port: process.env.DBPORT,
user: process.env.DBUSER,
database: process.env.DBNAME,
password: process.env.DBPASSWORD
});
console.log("isFavorite logged on to db");
let selectQuery = 'SELECT COUNT(*) c FROM Favorites WHERE userID = ? AND petID = ?';
let query = mysql.format(selectQuery,[req.body.userid, req.body.petid]);
conn.query(query,(err, response, fields) => {
if(err) {
console.log(err);
res.status(500).send("Error querying database.");
return;
}
// rows added
console.log("isFavorite");
console.log(response.length);
if (response.length > 0) {
console.log(JSON.stringify(response));
res.status(200).json({IsFavorite: response[0].c >= 1});
} else {
res.status(200).json({IsFavorite: false});
}
});
} catch (err) {
next(err);
}
});
let PORT = process.env.PORT || 3000;
let IP = process.env.IP || '127.0.0.1';
app.listen(PORT, IP, () => {
console.log('Server is running at port ' + PORT + ' and IP = ' + IP);
});

Unable to fetch data from workbench Mysql using node js

// import express js
const express = require('express')
// import a body-parser
const bodyparser = require('body-parser');
// executing the express js
const app = express();
// import mysql packages
const mysql = require('mysql');
// use bodyparser in express
app.use(bodyparser.json);
// create an connection details for mysql database
var mysqlConnection = mysql.createConnection(
{
host:'localhost',
user:'root',
password:'keerthi#abitech',
database:'employeedb'
}
)
// To connect with mysql database
mysqlConnection.connect((err)=>{
if(!err)
console.log('DB is connected')
else
console.log('DB connection is failed \n Error: ' + JSON.stringify(err, undefined, 2));
});
// establish an data fetch from database
app.get('/employees', (res, req)=>{
mysqlConnection.query('SELECT * FROM employee', (err, results)=>{
if(err) throw err;
console.log(results);
res.send("post is send")
})
});
// creating an server
app.listen(3000, ()=>console.log("server is running in port number 3000"));
This is my code. I am not able to fetch an data from mysql workbench.
The page is loading only does not give any response.
If i pass the link in postman it shows like this
Could Not Get Any Response
You are currently not sending your data back to the endpoint. Assuming that your connection is successful, you should res.send(results) instead of res.send("post is send") in order to send your results to the /employees endpoint.
Hope this fixes your problem.

How to resolve 502 Mysql query error on Netlify (Express server)

I have a React app + Express server deployed on netlify here. I have a simple api endpoint that queries my MySql DB on AWS.
When I make the api request I am given a "Failed to load resource: the server responded with a status of 502".
If I just return a simple
res.send("simple response")
then everything works fine and I get the response on the client. Could someone point me in the right direction on what I should be looking for?
I've tried to disable the skip_name_resolve parameter on my db to see if the hostname mattered, opening up access to all ports / ip's on the aws security group, look up common examples of express + mysql server implementations, lookup the netlify function docs, and using async await in the server.
// client.jsx
useEffect( () => {
fetch("/.netlify/functions/server/api/getSalesData")
.then(res => res.json())
.then(res => console.log(res));
// server.js
const express = require("express");
const bodyParser = require("body-parser");
const serverless = require('serverless-http');
const mysql = require("mysql");
const db = mysql.createConnection({ ... });
db.connect(function(err) {
if (err) throw err;
console.log('You are now connected...')
});
const app = express();
const router = express.Router();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
router.get("/api/getSalesData", (req, res) => {
// res.send({ express: "Hello from express" });
db.query("SELECT * FROM Sales LIMIT 5", (err, rows) => {
if (err) throw err;
res.send(rows);
});
});
app.use('/.netlify/functions/server', router);
module.exports = app;
module.exports.handler = serverless(app);

How to connect mysql with nodejs?

I just started to learn nodejs with express framework.In my app there are two pages app.js and db.js..I need to post data from form and insert to register table
In db.js
var mysql = require('./node_modules/mysql');
var connection = mysql.createConnection({
host: '127.0.0.1',
user: 'root',
password: '',
database: 'nodeapp'
});
connection.connect(function (err) {
if (err)
throw err;
});
module.exports = connection;
// In my app.js page
var express = require('./lib/express');
var app = express();
var bodyParser = require('body-parser')
var db = require('/db');
app.get('/', function (req, res) {
res.sendFile('/NodeProj/views/' + 'index.html');
});
/** bodyParser.urlencoded(options)
* Parses the text as URL encoded data (which is how browsers tend to send form data from regular forms set to POST)
* and exposes the resulting object (containing the keys and values) on req.body
*/
app.use(bodyParser.urlencoded({
extended: true
}));
/**bodyParser.json(options)
* Parses the text as JSON and exposes the resulting object on req.body.
*/
app.use(bodyParser.json());
app.post('/process_form', function (req, res) {
var response = {
"firstname": req.body.fst_name,
"email": req.body.fst_email,
"password": req.body.fst_password
};
var query = connection.query('INSERT INTO register SET?',response,function(err,result){
if(err) throw err;
if(result) console.log(result);
});
res.end(JSON.stringify(response));
});
app.listen(8081);
But when I run the code I got the following error
Refference error: connection is not defined
Please help me .Thanks in advance.
As mentioned in the comments, you've called connection db.
So if you replace var db = require('/db'); with var connection = require('./db'); then your connection will be defined.