Search code examples
node.jsweb-applicationsmysql-workbenchazure-database-mysql

Azure Database for MySQL - webapp nodejs


So I have been working on a web app with local mysql workbench. I recently moved the database to Azure Database for MySQL. Everything was working properly before I moved away from local. All my webpages were working properly, now only 2 out of the 4 pages work and I am running into the error below when I click on the broken pages. Below is how I am connecting to the database, I am not sure if the second connection is working.

Do I need to do something like this?
https://learn.microsoft.com/en-us/azure/mysql/howto-configure-ssl

Thank you for any help!

var connection = mysql.createConnection({
       host: 'host',
       user: 'user',
       password: "password",
       database: 'schema_1',
       ssl: true
    });
var connection = mysql.createConnection({
       host: 'host',
       user: 'user',
       password: "password",
       database: 'schema_2',
       ssl: true
    });

enter image description here enter image description here enter image description here enter image description here

EDIT HERE ------------------------

table_routes.js

var express = require('express')
     , http = require('http')
     , mysql = require('mysql'); // <---- HERE
   
    var app = express();
    const fs = require('fs');
    const path = require('path');
   
    
   
    app.use(function(req, res, next) {
       res.header("Access-Control-Allow-Origin", "http://127.0.0.1:3000");
       res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
       next();
     });
   
    var connection = mysql.createConnection({
       host: 'host',
       user: 'root',
       password: "password",
       database: 'db1',
       ssl: {
         ca: fs.readFileSync(path.resolve(__dirname, 'BaltimoreCyberTrustRoot.crt.pem'))
      }
      
    });

connection.connect(); // <---- AND HERE
   
    // all environments
    app.set('port', process.env.PORT || 7003);

table_routes2.js

var express = require('express')
     , http = require('http')
     , mysql = require('mysql'); // <---- HERE
   
    var app = express();
    const fs = require('fs');
    const path = require('path');
   
    
   
    app.use(function(req, res, next) {
       res.header("Access-Control-Allow-Origin", "http://127.0.0.1:3000");
       res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
       next();
     });
   
    var connection = mysql.createConnection({
       host: 'host',
       user: 'user',
       password: "password",
       database: 'db2',
       ssl: {
         ca: fs.readFileSync(path.resolve(__dirname, 'BaltimoreCyberTrustRoot.crt.pem'))
       }
    });
   
    connection.connect(); // <---- AND HERE
   
    // all environments
    app.set('port', process.env.PORT || 7004); 

enter image description here


Solution

  • Newest

    I suggest you use sequelize to connect multiple databases. Only need to configure the database in config.js. Not the way you used 7003 and 7004 to define multiple databases.

    My sample code demonstrates connecting two databases in mysql and sqlsever.The following figure is the operation result. It just demo code, if you want to use it in your project, you need learn it.

    enter image description here

    The structure of my demo directory is as follows.

    enter image description here

    config.js

    const fs = require('fs');
    const path = require('path');
    
    module.exports = {
    
    /**Declaration of databases for my development environment**/
      "development": {
          "databases": {
              "dbinmysql": {
                  "database": "mysql", //you should always save these values in environment variables
                  "username": "***@p***mysql",  //only for testing purposes you can also define the values here
                  "password":  "Ja***",
                  "host": "*****mysql.mysql.database.azure.com",
                  "port": 3306,
                  "ssl":true,
                  "dialect": "mysql",  //here you need to define the dialect of your databse, in my case it is Postgres
                  "dialectOptions": {
                    ssl: {
                        ca: fs.readFileSync(path.resolve(__dirname, 'BaltimoreCyberTrustRoot.crt.pem'))
                      }
                  },
              },
              "dbinsqlserver": {
                  "database": "pa*****db", 
                  "username": "pa***i",  
                  "password":  "J*****0",
                  "host": "***sqlserver.database.windows.net",
                  "port": 1433,
                  "dialect": "mssql",  //second database can have a different dialect
                  "dialectOptions": {
                    options: {
                        encrypt: true,
                    }
                }
              },
          },
      }
      }
    

    test.js

    const Sequelize = require('sequelize');
    const env = process.env.NODE_ENV || 'development';
    const { QueryTypes } = require('sequelize');
    
    //Load the configuration from the config.js
    const config = require(`./config.js`)[env];
    
    //Create an empty object which can store our databases
    const db = {};
    
    //Extract the database information into an array
    const databases = Object.keys(config.databases);
    
    //Loop over the array and create a new Sequelize instance for every database from config.js
    for(let i = 0; i < databases.length; ++i) {
        let database = databases[i];
        let dbPath = config.databases[database];
        console.log("try to connecting "+database);
        //Store the database connection in our db object
        db[database] = new Sequelize( dbPath.database, dbPath.username, dbPath.password, dbPath );
        if (database == 'dbinmysql') {
            const results = db[database].query("SELECT *FROM USER", { type: QueryTypes.SELECT })
        } else if (database == 'dbinsqlserver') {
            const results = db[database].query("SELECT *FROM TEST", { type: QueryTypes.SELECT })
       }
    }
    

    PRIVIOUS

    I think the root cause is that when you publish your webapp to azure, there is only one port that table_routes_1and2.js finally listens to, http_80 and https_443, there should be only one db that finally takes effect, this should be the root cause.