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

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

Related

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!

Connection to mysql works fine locally but not as AWS lambda function

I've created a simple mySQL database that I'm trying to access data from via an AWS Lambda function.
This is a version of the code that runs fine locally:
var mysql = require('mysql');
var config = require('./config.json');
var pool = mysql.createPool({
host : config.dbhost,
user : config.dbuser,
password : config.dbpassword,
database : config.dbname
});
pool.getConnection(function(err, connection) {
// Use the connection
connection.query("SELECT username FROM ClimbingDB.users WHERE email = 'testemail1'", function (error, results, fields) {
// And done with the connection.
connection.release();
// Handle error after the release.
if (error) throw error;
console.log(results);
process.exit();
});
});
This is that code converted to work with AWS Lambda:
var mysql = require('mysql');
var config = require('./config.json');
var pool = mysql.createPool({
host : config.dbhost,
user : config.dbuser,
password : config.dbpassword,
database : config.dbname
});
exports.handler = (event, context, callback) => {
//prevent timeout from waiting event loop
context.callbackWaitsForEmptyEventLoop = false;
pool.getConnection(function(err, connection) {
if (err) return callback(err)
// Use the connection
connection.query("SELECT username FROM ClimbingDB.users WHERE email = 'testemail1'", function (error, results, fields) {
// And done with the connection.
connection.release();
// Handle error after the release.
if (error) return callback(error);
else return callback(null,results);
});
});
};
Which times out with this error message:
{
"errorMessage": "2019-07-19T17:49:04.110Z 2f3e208c-62a6-4e90-b8ec-29398780a2a6 Task timed out after 3.00 seconds"
}
I'm not sure why it doesnt seem to be able to connect. I tried adding the function to a vpc and a security group that has access to RDB's, neither of which do anything. I'm not sure what I'm doing wrong here.
You will need:
The Amazon RDS instance in the same VPC as the AWS Lambda function
A security group on the Lambda function (Lambda-SG)
A security group on the RDS instance (DB-SG) that permits inbound connections on port 3306 from Lambda-SG
That is, DB-SG should specifically reference Lambda-SG (it will turn into a security group ID in the format sg-1234).
You might also want to increase the timeout of the Lambda function to give it a bit more time to run.

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.

Angular 4 - display date from database

I need display data in table from MySql database, but I dont know how it do this.
I tried found something example or example application with source code, but I nothing found.
Maybe someone help me with this?
I tried with node.js express:
var mysql = require('mysql');
var https = require('https');
var con = mysql.createConnection({
host: "https://adress to database",
user: "user",
password: "password",
database: "db"
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
});
But i get error:
Error: getaddrinfo ENOTFOUND
here is a simple way to get data from mySQL and export it as json:
var http = require('http');
var mysql = require('mysql');
var bodyParser = require("body-parser");
var express = require('express');
var app = express();
var pool = mysql.createPool({
host: 'db location',
user: 'username od db',
password: 'something',
database: 'yourdatabase',
port:3306
});
// define rute
var apiRoutes = express.Router();
var port = 9000;
apiRoutes.get('/', function (req, res) {
res.json({ message: 'API works' });
});
apiRoutes.get('/data', function (req, res, next) {
pool.getConnection(function (err, connection) {
if (err) {
console.error("error hapened: " + err);
}
var query = "SELECT * FROM imena ORDER BY id ASC";
var table = ["imena"];
query = mysql.format(query, table);
connection.query(query, function (err, rows) {
connection.release();
if (err) {
return next(err);
} else {
res.json({
success: true,
list_users: rows
});
}
});
});
});
app.use('/api', apiRoutes);
// starting
app.listen(port);
console.log('API radi # port:' + ' ' + port);
But i still suggest that you start using noSQL databases like firebase because of they are simple and faster.
In order to show data from MySQL Database, you need to provide application interface(s) to Angular environment and only then Angular can use the data. There are few techniques in which you can design interfaces, REST is the most popular though.
First you need to understand that Angular is Front-End framework and it can only send requests to backend such as Node js, PHP etc.Thus, first you need to chose your backend. Node is popular with express js module, but if you still don't have mySQL set, go for firebase real time database. If you decide node js => express => mySQL check tutorial online.

Node.js http with mysql pooling quits unexpectedly on error

So I started to try node.js this morning and was able to come-up with a http service that handles path requests and can connect to mysql with pooling for multiple transactions.
I am just having problems if ever I tried to make the password wrong, etc the node process quits unexpectedly.
var http = require("http");
var url = require("url");
var mysql = require('mysql');
var pool = mysql.createPool({
host : 'localhost',
user : 'root',
password : 'root',
database : 'test'
});
...
var pathname = url.parse(request.url).pathname;
var url_parts = url.parse(request.url, true);
var query = url_parts.query;
...
var table = query.table;
var sql = "SELECT * FROM " + table + "";
...
pool.getConnection(function(err, connection) {
console.log(err);
connection.on('error', function(err) {
console.log(err.code);
});
// Use the connection
connection.query(sql, function(err, rows) {
if (err) throw err;
console.log(rows);
response.writeHead(200, {
"Content-Type" : "application/json"
});
response.write(JSON.stringify(rows, null, 0));
connection.end();
response.end();
});
console.log(connection.sql);
console.log(connection.query);
});
Appreciate any help on how can I make it not to QUIT! and just say the damn error.
Anyway, I used forever to make this node.js to never quit on me, in-cases of error.
You use throw err, but don t catch it anywhere, causing node a UncaughtException Error, closing the app.