How to connect to VM hosted MySQL using Node.js in Azure Function

Recently, some customers asked for a demo about how to connect to VM hosted MySQL using Node.js in Azure Function, so this article provides a simple demo describes how to connect to VM hosted MySQL using Node.js in Azure Function.

Prerequisites:

A VM hosted MySQL server with remote connection allowed for user root :

Procedures:

1.Create a JS Webhook connect, my function name is “testMysqlConn”:

2.Paste code below into the function(this function will connect to the VM hosted MySQL server and then execute sql in request body):

module.exports = function (context, req) {
 context.log('JavaScript HTTP trigger function processed a request.');

 var mysql = require('mysql');
 
 //type your host , username & password to connect to MySQL
 var con = mysql.createConnection({
 host: "<your mysql server host/ip address>",
 user: "<your mysql user name>",
 password: "<your mysql password>"
 });

 con.connect(function (err) {
 if (err) throw err;
 context.log("Connected!");

 //Query MySQL and return the result
 con.query(req.body.sql, function (err, result) {
 if (err) throw err;
 var jsonresp = "";
 for (var i in result) {
 jsonresp += "user:" + result[i].user + " password:" + result[i].password +"| ";
 }
 context.res = {
 body: jsonresp
 };

 context.done();
 });
 });
};

Note : Before we test the function , we should import related modules, since the sample code depends on mysql module.

1.Go to kudu and then click “Debug Console” => “CMD” :

2. Go to you function project folder and run :

npm install mysql

3. Once imported , back to Portal , let’s test the function , use POST method to call this function with request body :

{
"sql": "select user,password from mysql.user"
}

here is the response :

"user:root password:*6BB4837EB74329105EE4568DDA7DC67ED2CA2AD9|  user:root password:|  user:root password:|  user: password:|  user:pma password:|  user:root password:*6BB4837EB74329105EE4568DDA7DC67ED2CA2AD9|  "

Let’s run the same sql query on mysql console to have a check:

OK, we connect to VM hosted MySQL using nodejs in Azure Function successfully.

Summary

This is a simple demo describes how to connect to VM hosted MySQL using Node.js in Azure Function.

If you have any questions, please contact us via aka.ms/devchat.

 

Leave a Reply

Your email address will not be published. Required fields are marked *