I am working on a course project using Vue.js to create the front-end web application. I am extremely new with how the front and back ends speak to each other. My teammate created the Node.js code below (sensitive information left out):
const mysqlssh = require('mysql-ssh');
const fs = require('fs');
var commands = require('./commandList');
var command = commands.cmd;
var output;
mysqlssh.connect(
{
host: 'address',
user: 'root',
password: 'pwd'
},
{
host: 'localhost',
user: 'root',
password: 'pws',
database: 'db-name'
}
)
.then(client => {
client.query(command, function (err, results, fields) {//command is query
if (err) throw err//throws error if anything in the connection goes wrong
console.log(results);//logs results of query
output = JSON.stringify(results);//output = results of query
// var i = output.lastIndexOf('"');//gets last "
// output = output.slice(0, i);//slices off last " and everything after it
//i = output.lastIndexOf('"');//gets new last "
// output = output.slice(i+1, output.length);//slices new last " and everything before it
// console.log(output);//prints output to console
mysqlssh.close()//close sql ssh
})
})
.catch(err => {
console.log(err)
})
The file works just fine when running node db.js
However, when I attempt to use import
or require
or even copy and paste this into my App.vue file, the project throws a compile error that is not descriptive:
WARNING: in ./node_modules/defaultable/defaultable.js
Critical dependency: the request of a dependency is an expression
Compile Error
And when viewing the project within the browser, I see this error in the Console:
Uncaught Error: Cannot find module 'net'.
Browser Error
This appears it is part of the net
module of Node.js and as I understand it, this cannot run on the browser. I am not looking for code critique, but I would like to know if there is a way to implement this setup without reworking the code that connects to the MySQL database.
The answer after hours of toiling is to standup another package that runs node server separately using Express as a router ending up with something like this:
const express = require('express');
const mysqlssh = require('mysql-ssh');
const router = express.Router();
var output;
// Get App User
router.get('/user', (req, res) => {
var query = "SELECT * FROM APPUSERS WHERE EMAIL = 'sample@email.com';";
var result = connectAndQuery(query);
setTimeout(function(){
res.send(output);
}, 3000);
});
function connectAndQuery(command) {
mysqlssh.connect(
{
host: 'address',
user: 'root',
password: 'pwd'
},
{
host: 'localhost',
user: 'root',
password: 'pwd',
database: 'db-name'
}
)
.then(client => {
client.query(command, function (err, results) {//command is query
if (err) throw err;//throws error if anything in the connection goes wrong
output = JSON.stringify(results);
mysqlssh.close();//close sql ssh
return output;
})
})
.catch(err => {
console.log(err)
})
}
module.exports = router;