Azure Function not connecting to mysql after deploy NodeJS - mysql

I've made a simple Azure function that when executed will run an insert query to a MySQL database. The MySQL database lives on a HostGator server (shared plan). The Azure function I wrote is able to insert to the DB table as expected when running locally, but after I deploy to Azure the function appears to run fine, but then no new records show in the database table.
Below is the function code:
const mysql = require('mysql');
module.exports = async function (context, req) {
var connection = mysql.createConnection({
host: '*****************',
user: '*************',
password: '*************',
database: '***************'
});
connection.connect();
const insertQuery = `INSERT into emails (email_address, first_name, last_name, preferred_game, date_joined) VALUES ('bob#example.com', 'Bob', 'Jones', 'both', NOW());`;
await connection.query(insertQuery, function (error, results, fields) {
if (error) throw error;
});
connection.end();
context.res = {
// status: 200, /* Defaults to 200 */
body: '200'
};
}
The strange thing is that I don't see any errors in the logs anywhere, so it appears to work, but when I look in the DB no new records have been inserted. I thought at first it might be an IP whitelist issue, but after adding the Azure Function App IP it still failed to insert a record to the DB (Virtual IP as shown under app properties in the Azure portal).
I can't think of why else this wouldn't be able to insert records to the DB from the deployed Azure function.

What you've whitelisted, sounds like the "Inbound" IP address. It may be because you haven't whitelisted your "outbound" IP address(es).
Get the outbound IPs with az CLI
az functionapp show --resource-group <GROUP_NAME> --name <APP_NAME> --query outboundIpAddresses --output tsv
Or get the outbound IPs in the portal properties (where you found Virtual IP).
See here for more details

Related

Trying to connect the mySQL database on Railway to the backend of my React App built in Next.js but no data is showing up

I have linked my local mySQL workbench database to the deployment website "railway" - they are working and connected. If I edit one database the other updates automatically.
However in my app when I try to connect to the database now being hosted on railway my data is not displayed. If I revert to my local database it works fine.
This works okay
const db = mysql.createConnection({
host: "localhost",
user: "root",
password: "password",
database: "flashcards_2.0",
});
app.get("/ClassSelector/:yearId/:weekId/:classId", function (req, res) {
const yearId = req.params.yearId;
const weekId = req.params.weekId;
const classId = req.params.classId;
const q = `SELECT * FROM ${classId} WHERE year = ${yearId} AND week = ${weekId}`;
db.query(q, (err, data) => {
if (err) return res.json(err);
console.log(data);
res.json(data);
});
});
This is the data I tried with the hosted server
The railway gives me these two pieces of data in relation to the database - I have starred out the password but otherwise it is identical
mysql -hcontainers-us-west-19.railway.app -uroot -pnkEDYn2av******* --port 6177 --protocol=TCP railway
mysql://root:nkEDYn2av*******#containers-us-west-19.railway.app:6177/railway
Here is my code that I swapped in to try and the hosted server
const db = mysql.createConnection({
host: "containers-us-west-19.railway.app",
user: "root",
password: "nkEDYn2av*********",
database: "railway",
});
The axios.get() on the client side was still looking at localhost and not the http of the new hosted website. I thought that fixed it but didn't.
I still have the same problem – I still cannot seem to access the database being hosted on railway – but I am getting a new error.
This is my app
https://eb-flashcards.vercel.app/
Here is the link that should retrieve the flashcards I want...
https://ebflashcards.vercel.app/ClassSelector/2022/35/Listening%20Kiso

is it possible to connect to mysql database directly without rest api?

I'm very new to this backend stuff but I really want to know or else I can't sleep tonight or many other nightss.......
I'm tasked to build a rest API that will allow our web application to update our company's MySQL database remotely from any internet or client.
basically, the web application will be built using react framework that will allow users to take in some inputs and send them to the backend and update the MySQL database remotely.
so far, I have the rest API ready and inside this rest API i have included some mysql methods that will update the table in our database. it works fine.
but suddenly I couldn't find the reason why we need the rest API in the first place
below is the code I have...my question is
can't we just skip the express part? and directly connect the application to MySQL database using the mysql methods createConnection and then run db.query(sqlInsert) without running the app.get?
the only reason I can think of is that, if I do this, it will probably allow anyone to access the database from the browser's console. In this case, does it mean rest API is just like a filter that simply runs a server site after the user clicks the submit button, and then once the server runs it will then take the submitted information and run the db.query()? and then once that is complete, it will send back a response displayed on the server site saying its working?
const express = require('express');
const app = express();
const mysql = require('mysql');
const db = mysql.createConnection({
host:'the ip address of the computer that has the mySQL database',
user: 'the user name created in workbench',
password: 'the password created in workbench',
database: 'the database name',
port: '1234'
})
db.connect(function(err){
if(err){
console.log(err)
process.exit(1)
}
console.log("connected to mysql")
})
app.get('/', (req,res) => {
const sqlInsert = "INSERT INTO person123 (customerid, firstname, lastname) VALUES ('USv10', 'USv10', 'USv10');"
db.query(sqlInsert), (err, result) =>{
}
res.send('working')
})
app.listen(3001, () => {
console.log ('running on port 3001 yes')
})
yes you can connect with mysql without express and running restful api but
condition is that server will be running using a specific port.with only this block
of code your server is connected to databse.
var mysql = require('mysql');
var con = mysql.createConnection({
host:'the ip address of the computer that has the mySQL database',
user: 'the user name created in workbench',
password: 'the password created in workbench',
database: 'the database name',
port: '1234'
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
});
and this block is nesecary for running server on specific port
app.listen(3001, () => {
console.log ('running on port 3001 yes')
})

Inserting Values into MySQL DB using NodeJS Not Working

Currently I am experiencing a very frustrating issue with inserting data into my MySQL db using my NodeJS Express server.
My current setup is the following:
• MySQL server db on DigitalOcean droplet.
• NodeJS Express server on the same DigitalOcean droplet. It is being proxied by my Apache server that is on the same droplet. I keep Node server running with PM2.
I have been able to successfully read data from my db (i.e. SELECT * from performance);).
However, no matter what I try I cannot insert any data into my db. I have tried countless different solutions but none have worked.
Help would be greatly appreciated. Please ask any questions for further clarification if needed. Thank you.
My current code relating to MySQL:
server.js
var mysql = require('mysql');
var con = mysql.createConnection({
host: 'localhost',
user: 'user',
password: 'password',
database: 'analytics',
supportBigNumbers: true,
debug: true,
});
server.post('/performance', (req, res) => {
let d = req.body;
con.connect(function (err) {
if (err) throw err;
let q =
'INSERT INTO performance (uid, reqStart, resEnd, loadDuration) VALUES ?';
let values = []; // values to be inserted into db
// for testing purposes I have commented this out and tried inserting a hardcoded set of values instead
/*let body = JSON.parse(req.body); // json string body to json obj
body.data.forEach((x) => {
values.push([body.uid, x.reqStart, x.resEnd, x.loadDuration]);
});*/
values = [
[23299730, 8.3282343284, 8.121252244, 2.238932989],
[23288734, 8.3282343284, 8.121292244, 2.238932989],
];
con.query(q, [values], function (err, result) {
if (err) throw err;
});
});
res.send(d);
});
Update: I just ran my server manually (without PM2). This has allowed me to view console messages. For the first time I have seen a successful insert query. And upon running the server with PM2 I also get a successful query. However, on the second attempt I get PROTOCOL_ENQUEUE_HANDSHAKE_TWICE error.
Based on multiple other posts/articles I thought my code avoided this problem, but it's erroring on the line where I call con.connect(...). I have con.connect in a server.get route, but I haven't been hitting that endpoint at all.
After many hours of debugging, I think I found the problem.
Almost all tutorials showing how to connect to MySQL db using Node show that you should embed a con.query() call within a con.connect() call, and using connect() is recommended on MySQL docs.
However, con.query() also establishes a connection. Maybe it's because I am keeping the server live across multiple calls, but this results in the Handshake error I described in the post. Removing the wrapping con.connect() call fixed my problem.

How to use Auth0's custom database to add a user to a MySQL database?

I am using Auth0 for a login service but I have a need to add a user to a database in MySQL every time an account is registered through Auth0.
They give this following script template but I am a newbie and need help debugging and understanding it. My specific questions are detailed as comments:
function create(user, callback) {
var connection = mysql({
host: 'localhost', //what should this be?
user: 'KNOWN/Understood',
password: 'KNOWN/Understood',
database: 'KNOWN/Understood'
});
connection.connect();
var query = "INSERT INTO users SET ?"; //what does this do?
bcrypt.hash(user.password, 10, function (err, hash) { //what does this do?
if (err) { return callback(err); }
var insert = {
password: hash,
email: user.email
};
connection.query(query, insert, function (err, results) {
if (err) return callback(err);
if (results.length === 0) return callback();
callback(null);
});
});
}
Is there anything else I need to change for this script or understand or call in for it to work?
I often get the error missing username for Database connection with requires_username enabled and I'm unsure what this means.
I'm assuming you already went through this tutorial on custom databases so let's address your specific questions.
host: 'localhost' // What should this be?
This and the other properties of this object define the way to connect to your custom MySQL database. The database needs to be reached from within Auth0 servers so this needs to be a host name accessible from the Internet.
"INSERT INTO users SET ?"; // What does this do?
This defines an SQL insert command that uses ? as a placeholder for later substitution.
If you see where this query is later used, you will noticed it's invoked with an additional insert object parameter that will cause the above query to be expanded into something like:
INSERT INTO users SET email = 'user#example.com', password = 'asdf34ASws'
bcrypt.hash(user.password, 10, function (err, hash) // What does this do?
This hashes the user provided password so that it's not stored in plain text in the database.
If you chose to require a username in addition to email you need to address this in your custom scripts as I believe the default templates assume that only email will be used.
This means that when creating the user in your database you also need to store the username and in the script to verify a user you also need to return the username.

Connecting to RDS database from node.js

I am trying to learn node.js so that I can actually get started on working on my personal project. I have been trying to follow the examples in the book "Learning node.js" (by Marc Wandschneider). I, at this point, decided to forgo practicing his example, and go straight into using his code as framework for my practice code.
In my practice code, all I am trying to do is connect to my RDS database (no, I am not using Elastic Beanstalk, btw), and output contents of one of the tables. Seems simple enough, but when I whip up the code for it (based on the book), it seems to attempt connection, but get hung up in the process. This is my code:
var pool = require('generic-pool');
var async = require('async');
var mysql = require('mysql');
var host = "<database-name>.cu8hvhstcity.us-west-2.rds.amazonaws.com",
database = "<database-name>",
user = "<username>",
password = "<someLongPassword>";
var dbClient;
async.waterfall([
// 1. establish connection to database
function (callback) {
console.log("Connecting to database " + database + "...");
dbClient = mysql.createConnection({
host: host,
database: database,
user: user,
password: password,
port: 3306
});
dbClient.connect();
},
// 2. select all from a table (let's go for locations)
function (cb)
{
var query = "SELECT * FROM locations"
console.log("running query \"" + query + "\"...");
dbClient.query(query, cb);
},
function (rows, fields, callback)
{
console.log(fields);
for (var i = 0; i < rows.length; i++)
{
console.log(JSON.stringify(rows, null, '\t'));
}
}
], function (err, results) {
if (err)
{
console.log("An error occurred...");
console.log(err);
}
else
{
console.log("Everything successfully completed!");
}
dbClient.end();
})
This is better than first attempt, when I put a database member to the argument passed to mysql.createConnection(), and it complained that database was unknown. In neither case did either "An error occurred..." nor "Everything successfully completed!" output to the window.
Is there any async stuff going on that is resulting in some kind of non-terminating infinite loop or something? How do I fix this?
The book has an associated GitHub page
NOTE:
Neither my example nor the cited GitHub code make use of that pool variable, so it can simply be commented out. All you need to do to run this yourself is to say npm install async,npm install mysql (as well as creating a dummy RDS database to point to, that contains locations table) before copying, pasting, and running this code.
EDIT:
I fixed the issue with database. I realized that the name of the database used '_', not '-'. Same issue (code hangs) still persists...
I did the following:
In the second function in the array, I needed two parameters, not one.
I fixed thus:function(results, cb)
The third function simply needed to callback(null)