establishing a connection to database using environment variables - mysql

I'm creating an API for my app that fetches some data from my amazon db.
I have added environment variables to a custom.sh file in profile.d on my server. The weird thing is, I can print out those variables from my api, but the only variable that works when creating the connection is the user variable.
When I hard code the database credentials in the connection string it works just fine.
here is my custom.sh where I declare the environment variables
#custom environment variables, with the actual values removed
export DB_HOST=value1;
export DB_PASS=value2;
export DB_USER=value3;
export DB_NAME=value4;
here is my nodejs expressjs api file
var express = require('express');
var app = express();
var mysql = require('mysql');
var DB_HOST = formatEnvironmentVariable(process.env.DB_HOST);
var DB_USER = formatEnvironmentVariable(process.env.DB_USER);
var DB_PASS = formatEnvironmentVariable(process.env.DB_PASS);
var DB_NAME = "'"+process.env.DB_NAME+"'";
function formatEnvironmentVariable(env) {
env = "'"+env+"'";
return env
}
var pool = mysql.createPool({
host : DB_HOST,
user : DB_USER,
password : DB_PASS,
database : DB_NAME,
connectionLimit: 100,
debug: false
})
function QueryTheDatabase(req, res, querystring) {
pool.getConnection(function(err,connection){
if (err) {
connection.release();
res.json({"code" : 100, "status" : "Error in connection database"});
return;
}
console.log('connected as id ' + connection.threadId);
connection.query(querystring,function(err,rows){
connection.release();
console.log("error? "+err);
if(!err) {
res.json(rows);
}
});
connection.on('error', function(err) {
console.log("error");
res.json({"code" : 100, "status" : "Error in connection database"});
return;
});
});
}
app.get('theurl', function(req, res) {
QueryTheDatabase(req, res, "the query that works fine");
});
var server = app.listen(3000, function () {
var host = server.address().address;
var host = server.address().port;
});

I'm not exactly sure why only the DB_USER variable is set properly (it may be that some other process is sending that information). If you're running your shell script as such:
$ ./custom.sh
It won't work. It's essentially creating a sub-shell and the exported variables are local to that shell (they won't affect the parent)
The only way to make environment variables accessible to your node process would be to source the file first.
$ source ./custom.sh

I got it to work finally, turns out I didnt need to add ' ' with my format function.
instead of
var DB_HOST = formatEnvironmentVariable(process.env.DB_HOST);
var DB_USER = formatEnvironmentVariable(process.env.DB_USER);
var DB_PASS = formatEnvironmentVariable(process.env.DB_PASS);
var DB_NAME = "'"+process.env.DB_NAME+"'";
I wrote
var DB_HOST = process.env.DB_HOST;
var DB_USER = process.env.DB_USER;
var DB_PASS = process.env.DB_PASS;
var DB_NAME = process.env.DB_NAME;

For this I'll suggest To use
config npm
https://www.npmjs.com/package/config

Related

How do format exports of multiple modules in NodeJS

I have the following code in my db.js file:
const mysql2 = require('mysql2/promise');
// Connect to server (locally for development mode) ----- NEW VERSIN
const pool = mysql2.createPool({
host : "ENDPOINT",
user : "admin",
password : "PASSWORD",
port : "3306",
database : "DATABASE",
waitForConnections: true,
connectionLimit: 10,
queueLimit: 0
});
module.exports = pool;
And in my app.js file I have:
const pool = require('./db');
async function checkUser(username) {
const result = await pool.query('SELECT * from users WHERE username = ?', [username]);
if (result[0].length < 1) {
throw new Error('Row with this username was not found');
}
return result[0][0];
}
async function check() {
let user = await checkUser("username");
console.log(user);
}
check();
But I'm getting the error:
(node:42037) UnhandledPromiseRejectionWarning: TypeError: pool.query is not a function
This is weird, because when I run all the code in the db.js file it works fine, so I'm probably messed up the export/require bit of it, please help!
ANSWER: HOW TO EXPORT MULTIPLE FUNCTIONS
In the document you are exporting, write as follows:
module.exports = {FunctionName1, FunctionName2, FunctionName3};
In the document you are importing to, write the following:
const {FunctionName1, FunctionName2, FunctionName3} = require('./whereyouareimportingfrom');
I had done the exports the wrong way, I tried exporting two functions by doing: "module.exports = ConnectDb, pool;" And that didn't work. When I removed the first function and only exported "pool" it worked.

How to store my session MySQL with express-mysql-session

see code below. its not storing a session in my database. I cant figure it. I have executiion file app.js. I have everythin setup and running but storing sessions in database dont work.. I posted the same question before but got no luck...
var express = require('express');
var mysql = require('mysql2');
var path = require('path');
var session = require('express-session');
var port = 3000;
var app = express();
var MySQLStore = require('mssql-session-store')(session);
app.use(session({
secret: 'tee tee',
resave: false,
saveUninitialized: false,
store: new MySQLStore(options)
}));
var connection = mysql.createConnection ({
host: 'localhost',
user: 'root',
password: '....',
database: 'node'
});
connection.connect(function(error) {
if(error) {
throw error;
} else {
console.log("We are now successfully connected with mySQL");
}
});
var options = {
connection: connection,
ttl: 3600,
reapInterval: 3600
};
app.get('/', (req, res) => {
res.sendFile('home.html', {
root: path.join(__dirname, './views')
});
});
app.listen(port, (req, res) => {
console.log('the server is running, ' + ' please, open your browser at http://localhost:%s', port);
});
It appears as you are using mssql-session-store (Microsoft SQL) to connect to MySQL.
Try using the npm package express-mysql-session:
https://www.npmjs.com/package/express-mysql-session
Like MySQL and MSSQL, there are many variants of SQL and SQL like databases so it is important you are precise with the database you are using.
Your line (below) should be the only issue. It is specifying the use of the Microsoft SQL session store package when you are trying to use the MySQL session store.
var MySQLStore = require('mssql-session-store')(session);
By changing it to
var MySQLStore = require('express-mysql-session')(session);
You specify the use of the mysql session store (Make sure you download the NPM package above first)

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.

Can't get and read GET request

I have a problem using Node.js. I am sending data via GET request to special script, which should read this data and write it in MySQL. Here is an example of GET request (very long):
http://demo.com/?&bssid=16~6D~57~7F~D8~AD&mac=60~01~94~2B~A8~85&rssi=0&hotspots_list=~~0_74~85~2A~39~77~48_-85~~~~1_78~8C~54~33~D8~3C_-91~~~
~2_64~6E~EA~0E~B3~26_-84~~~~3_76~85~2A~39~77~49_-87~~~~4_2C~33~7A~16~91~3B_-92~~~~5_54~BE~F7~6B~EE~43_-92~~~~6_98~DE~D0~AB~B8~64_-91~~~~7_14~DD~A9~1E
~F6~F8_-93~~~~8_64~6E~EA~0C~9A~3E_-84~~~~9_E8~DE~27~50~2A~12_-88~~~~10_84~C9~B2~0B~BA~C2_-81~~~~11_00~0F~94~BE~FC~44_-87~~~~12_56~BE~F7~6B~EE~44_-86~
~~~13_00~0E~8F~85~5F~73_-53~~~~14_0C~54~A5~A6~C1~1F_-87~~~~15_16~6D~57~7F~D8~AD_-78~~~~16_0E~54~A5~A6~C1~10_-92~~~~0_EC~1A~59~17~CF~5F_-91~~~~1_74~85
~2A~39~77~48_-92~~~~2_16~6D~57~7F~D8~AD_-77~~~~3_0C~54~A5~A6~C1~1F_-92~~~~4_0E~54~A5~A6~C1~10_-83~~~~5_84~C9~B2~0B~BA~C2_-82~~~~6_14~DD~A9~1E~F6~F8_-
92~~~~7_64~6E~EA~0C~9A~3E_-85~~~~8_E8~DE~27~50~2A~12_-93~~~~9_00~22~6B~56~2B~83_-92~~~~10_00~0E~8F~85~5F~73_-58~~~~11_00~0F~94~DB~DE~64_-91~~~~12_16~
DD~A9~1E~F6~F9_-92~~
I've done few experiments, and I found out, that it works fine in PHP, my code (only for output):
<?php
echo $_GET["bssid"]." ".$_GET["mac"]." ".$_GET["rssi"]." ".$_GET["hotspots_list"];
?>
But not in Node.js !This is my Node.js code:
var express = require("express");
var app = express();
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'host',
user : 'user',
password : 'pswd',
database : 'db'
});
var bssid, mac, rssi, hotspots_list;
const port = 3000;
const host = "0.0.0.0";
app.get('/', function (request, response) {
//Writing data to vars
bssid = request.query.bssid;
mac = request.query.mac;
rssi = request.query.rssi;
hotspots_list = request.query.hotspots_list;
//Sending request to MySQL server
connection.query(`INSERT INTO locations (mac, bssid_current, rssi_currnet, hotspots_list) VALUES ('${mac}','${bssid}','${rssi}','${hotspots_list}')`);
//Debugging line
console.log(`BSSID: ${bssid}`);
//Response
response.statusCode = 200;
response.setHeader('Content-Type', 'text/plain');
return response.send('Done');
});
app.listen(port, host, () => {
console.log(`Server running!`);
});
In your code, your route is /. And you are trying to access it via /server.js
Two solutions, either you add
app.get('/server.js', [...]) or you access it after removing server.js from your url.

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

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