Connectivity issue for MySQL 8.0 and Node JS using Express - mysql

I was trying out fetching the information from MySQL 8.0 table into Node JS using Express. But I am constantly getting the error ER_NOT_SUPPORTED_AUTH_MODE. I tried many things such as:
Changing the authentication method for an individual user (and used multiple different users) - changed it from SHA 256 to Caching 256 and to default one (mysql_native_password) neither of them works.
Changing my Node js code: instead of using the single connection which was giving me the error - PROTOCOL_ENQUEUE_AFTER_FATAL_ERROR, I changed it to pool of connection but still getting the error ER_NOT_SUPPORTED_AUTH_METHOD.
I found out that MySQL Server uses SHA 256 password private key and public key, but I don't know how to implement it or use it in Node. js.
My database table: react_test
product_id | product_name | product_price
1 | abc | 10
Here is my Node.js code:
const express = require('express');
const cors = require('cors');
const mysql = require('mysql');
const app = express();
const SELECT_ALL_QUERY = 'SELECT * FROM project.react_test';
const connection = mysql.createConnection({
host:'localhost',
user:'avd',
password:'password',
database:'project',
insecureAuth : true
});
const pool = mysql.createPool({
host : 'localhost',
user : 'avd',
password : 'password',
authentication_string : 'root',
insecureAuth : true
});
//var pool = mysql.createPool(connection);
connection.connect(err => {
if(err) {
return err;
}
})
console.log(connection);
app.use(cors());
app.get('/', (req,res) => {
res.send('hello from product server')
});
app.get('/hola', (req,res) => {
res.send('hola')
});
app.get('/hotels_info', (req,res) => {
connection.query(SELECT_ALL_QUERY, (err, results) => {
if(err){
return res.send(err)
} else {
return res.json({
data: results
})
}
});
});
app.listen(4000, () => {
console.log('Product server listining port 4000');
});
Error when using single connection: {"code":"PROTOCOL_ENQUEUE_AFTER_FATAL_ERROR","fatal":false}
Error when using pool of connection:
{"code":"ER_NOT_SUPPORTED_AUTH_MODE","errno":1251,"sqlMessage":"Client does not support authentication protocol requested by server; consider upgrading MySQL client","sqlState":"08004","fatal":true}
I dont know what to do further! Please guide me! Thank you in advance!

Related

React Native app connection to mysql - API for production

I have created my first app using expo and react native.
My backend is written in node.js (with express and axios) and connected to mysql database. I will be using get, post and put.
What I don't understand is how I move from a development environment to a production environment. In order to connect my API to an external server how do I go about setting up a baseURL which would replace my IP address and port in the below example?
Axios.post("http://53.183.245.150/:19056/location", body).then((response) => {
console.log(response);
}).catch(err => console.log(err))
I have searched online and all examples which they create an API only include running off the local server rather than creating a production app and setting up a remote server.
I would like to link the mobile app to my existing production DB (using mysql) and running off AWS. This DB is connected to my website which is up and running. My backend for my website is written in PHP.
Thank you for any guidance!
I have attached an example of my server as well.
const express = require('express');
const app = express();
const mysql = require('mysql');
const cors = require('cors');
app.use(cors());
app.use(express.json());
const db = mysql.createConnection({
user:'root',
host:'my ip address here',
password:'',
database: 'myDB',
});
app.post('/login', (req, res) => {
const user = req.body.user;
const password = req.body.password;
db.query('SELECT * FROM users WHERE uidUsers = ? AND pwdUsers = ?', [user, password], (error, rows, fields) => {
if (error) console.log(error);
if (rows.length > 0) {
res.send(rows);
} else {
res.send(rows);
}
});
})
app.get('/trips', (req, res) => {
const driver = req.query.driver;
const companyId = req.query.companyId;
const status1 = req.query.status1;
db.query('SELECT * FROM trips WHERE driver = ? AND company_id = ? AND status_1 = ?', [driver, companyId, status1], (error, rows, fields) => {
if(error) console.log(error);
else{
console.log(driver)
res.send(rows);
}
})
});
const PORT = process.env.PORT || 19056;
app.listen(PORT, () => {
console.log(`Listening on port ${PORT}`);
})

Unable to connect React Native app to MySQL database using Node.js. (Error: connect ECONNREFUSED 127.0.0.1:3306)

I am very new to programming so I do apologize if this is a really simple question.
So, I have been trying to connect my React Native application to the MySQL Database using Node and Express server, but I keep on getting the following error (I have checked other stackoverflow questions as well, but nothing has helped):
Error
I have checked my host name and port number multiple times and the all the information seems to be correct. I am not sure what is wrong with the following code:
var express = require("express");
var app = express();
var mysql = require("mysql");
var bodyParser = require("body-parser");
const { application } = require("express");
app.use(bodyParser.json({ type: "application/json" }));
app.use(bodyParser.urlencoded({ extended: true }));
var connection = mysql.createConnection({
host: '127.0.0.1', // Your connection adress (localhost).
port: "3306",
user: "root", // Your database's username.
password: "", // Your database's password.
database: "birthdays", // Your database's name.
});
connection.connect(function (error) {
if (error) console.log(error);
else console.log("connected");
});
// Starting our server.
app.listen(4547, () => {
console.log("Go to http://localhost:4547/dinners so you can see the data.");
});
app.get("/users", function (req, res) {
con.query("select * from users", function (error, rows, fields) {
if (error) console.log(error);
else {
console.log(rows);
res.send(rows);
}
});
});
I run this code by typing "node fileName.js" in the terminal.
I don't know if this is helpful, but I have also connected by MySQL database to MySQL Workbench.
Any help is appreciated!

React Native Access mysql db using express

I need to access my Data from my mysql Database using express, on my server the data is as a json, but when i try to access it i always get 'undefined' and my express server crash
the json i have on the server :
[{"idProjet":1,"nomProjet":"test","dateDebut":"2021-05-18T22:00:00.000Z","nomAuteur":"mathieu","prenomAuteur":"jean","organisme":"idmc"}]
fetching code :
let id = 'id :';
const [data, setData] = useState([]);
useEffect(() => {
fetch('http://localhost:3000/projets')
.then(response => {return response.json()})
.then((json => {console.log(json);setData(json);}))
.catch(error => console.error(error));
console.log(data);
}, []);
Route.js code :
const express = require('express');
const bodyParser = require('body-parser');
const mysql = require('mysql');
const connection = mysql.createPool({
host : 'localhost',
user : 'root',
password : '',
database : 'agora'
});
// Starting our app.
const app = express();
// Creating a GET route that returns data from the 'users' table.
app.get('/projets', function (req, res) {
// Connecting to the database.
connection.getConnection(function (err, connection) {
// Executing the MySQL query (select all data from the 'users' table).
connection.query('SELECT * FROM projet', function (error, results, fields) {
// If some error occurs, we throw an error.
if (error) throw error;
// Getting the 'response' from the database and sending it to our route. This is were the data is.
res.send(results)
});
});
});
// Starting our server.
app.listen(3000, () => {
console.log('Go to http://localhost:3000/projets so you can see the data.');
});
The most common problem for this type of behavior is that you are using react-native on an android emulator. Android Emulator is using an IP-address different from localhost on windows machine. For more information, check here the official documentation.
So you can forward your port on the same port used by the android emulator (10.0.2.2) or you can change the port to 80 so you won't have any problem
You can go check this answer here

Error connecting to MySQL from Node-JS server

I am learning to develop server on node-js and have developed a basic get function which retrieves data from MySQL DB hosted on a ubuntu server at digitalocean.
Here's my code:
const express = require('express')
const app = express()
const mysql = require('mysql')
const Client = require('ssh2').Client;
const ssh = new Client();
const db = new Promise(function(resolve, reject){
ssh.on('ready', function() {
ssh.forwardOut(
// source address, this can usually be any valid address
'localhost',
// source port, this can be any valid port number
3333,
// destination address (localhost here refers to the SSH server)
'xxx.xxx.xxx.xxx',
// destination port
22,
function (err, stream) {
if (err) throw err; // SSH error: can also send error in promise ex.
reject(err)
// use `sql` connection as usual
connection = mysql.createConnection({
host : '127.0.0.1',
user : 'user',
password : 'pass',
database: 'mysql',
stream: stream
});
// send connection back in variable depending on success or not
connection.connect(function(err){
if (!err) {
resolve(connection)
} else {
reject(err)
}
});
});
}).connect({
host: 'xxx.xxx.xxx.xxx', //IP address where DB is hosted
port: 22, //Port refering to the IP
username: 'user', //username to loginto the host
password: 'pass' //password to log into host
});
});
//Retrieve route
app.get('/users', (req, res) => {
//console.log("Fetching user with id: " + req.params.id)
const queryString = "SELECT * FROM user"
connection.query(queryString, (err, rows, fields) => {
if(err){
console.log("Failed to query " + err)
res.sendStatus(500)
return
}
console.log("Fetch Succesful")
res.json(rows)
})
})
app.listen(3000, () => {
console.log("Server is up and listerning on port 3000")
})
When I run this code on my local machine it is able to connect to external DB and fetch the data. I have created another server at digitalocean and hosted the same code. However upon running it I get error at connection stating: UnhandledPromiseRejectionWarning: Error: connect ECONNREFUSED 127.0.0.1:3306
I tried various solutions available on the platform but could not suceed.
I have written the code accoring to the documentation but still clueless what's causing the error.
Thank You.

Nodejs (Express) connecting MySQL - Local and Remote connection different?

guys. I am learning how to use Express to connect to remote MySQL. So, I started out doing it on my local machine (a local MySQL server). After I have succeeded on the local environment, I tried changing the the connection to a remote MySQL hosting (at DB4Free). Yes, I have succeeded on the localhost. However, whenever I run a Get/Post to the remote MySQL Server, my console show me the error below. I'll attach the related segment of codes below here. I have been trying it the whole afternoon.
Hope that someone here can enlighten on this matter. Thank you in advance guys :)
This is the error shown in my console
My file for connecting db is as below - ConnectionString.js
var mysql = require("mysql");
var pool = mysql.createPool({
connectionLimit : 100,
host : '85.10.205.173:3306',
user : '******* ',
password : '*******',
database : '*******',
});
exports.getConnection = function(callback) {
pool.getConnection(function(err, conn) {
if(err) {
return callback(err);
}
callback(err, conn);
});
};
Portion of my file for the routes and query is this
var express = require('express');
var router = express.Router();
var mysql = require('mysql');
var conn = require('../database/ConnectionString');
var result;
//Validate user login
router.get('/login', function(req, res, next) {
conn.getConnection(
function (err, client) {
client.query('SELECT * FROM mt_User', function(err, rows) {
// And done with the connection.
if(err){
console.log('Query Error');
}
res.json(rows);
client.release();
// Don't use the connection here, it has been returned to the pool.
});
});
});
Alright, I have found the issue. It seems that the mysql package in npm requires that the host and port to be defined separately. After tuning it to this code below for my ConnectionString.js file. It finally works.
var mysql = require("mysql");
var pool = mysql.createPool({
connectionLimit : 100,
host : '85.10.205.173',
port : 3306,
user : '*******',
password : '*******',
database : '*******',
});
exports.getConnection = function(callback) {
pool.getConnection(function(err, conn) {
if(err) {
return callback(err);
}
callback(err, conn);
});
};