How to use Mysql and MongoDB on same NodeJs server? - mysql

I have a REST API in NodeJS and Express JS. Here's the basic thing what I need to implement. There's a database in mysql and my node js server read the database in some specific conditions and need to make a log in MongoDB server. It is the architecture and it can't be changed. So is it possible to use both MySQL and MongoDB in same NodeJs server ?

Yes it's 100% possible, they use completely different ports and do not care about each other.
The server isn't a 'nodejs' server, it's a server that's running nodejs, and you can install anything you want on the server.

either you can directly write following mongodb and mysql database connection code in youe app.js (starter file) file
or you can write is separate files for mongo and mysql connection as follows:
step 1. create file named as mongodb_con.js
mongoose.connect('mongodb://localhost:27017')
.then(sucess => {
console.log("connected with mongo server...")
})
.catch(error => {
console.log("error while connecting to database...")
})
step 2. create file named as mysql_con.js
const mysql = require("mysql")
var con = mysql.createConnection({
host: "localhost", //your hostname
user: "root", //your username
password: "root", //your password
database: "detabase_name" //your database name
})
con.connect((error) => {
if (!error) {
console.log("connected with sql server")
}
else {
console.log("Error in Making Connection...", error)
}
})
step 3. in final stepjust import both file in app.js
const express = require('express')
const app = express()
require('./mongodb_con.js')
require('./mysql_con.js')
const port = 3000
app.get('/', (req, res) => {
res.send('Hello World!')
})
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})

Related

REACT NATIVE Retrieving data from localhost MySQL database

I'm writing an app in React Native and I have created a MySQL database to store my information, but I was wondering if it was possible to use axios or fetch to interact with my database since it's local and doesn't have an HTTP address yet?
I feel like I used to be able to do it, but I forgot the syntax to use... If anyone knows anything, I would greatly appreciate it.
Thank you
There is no direct connection between React Native and Mysql. So you need to use Node js.
Step 1:
npm install express
npm install body-parser
npm install mysql
Step 2:
const connection = mysql.createPool({
host : 'localhost', // Your connection adress (localhost).
user : 'root', // Your database's username.
password : '', // Your database's password.
database : 'my_db' // Your database's name.
});
// Starting our app.
const app = express();
// Creating a GET route that returns data from the 'users' table.
app.get('/users', function (req, res) {
// Connecting to the database.
connection.getConnection(function (err, connection) {
// Executing the MySQL query (select all data from the 'users' table).
connection.query('SELECT * FROM users', function (error, results, fields) {
// If some error occurs, we throw an error.
if (error) throw error;
// Getting the 'response' from the database and sending it to our route. This is were the data is.
res.send(results)
});
});
});
// Starting our server.
app.listen(3000, () => {
console.log('Go to http://localhost:3000/users so you can see the data.');
});
To get the data in your React Native App. You need to use your PC's IP Address. If you use localhost you access the smartphone/emulator localhost. Here is an example to follow:
getData(){
fetch('http://yourpcip:3000/users')
.then(response => response.json())
.then(users => console.log(users))

Encrypt DB password in NodeJS application before building and pushing docker image

Infrastructure setup:
Docker Desktop environment running on MacOS,
A Minikube cluster is also running on this MacOS.
Jenkins pod running on the Minikube cluster
I have this NodeJS application that talks to a MySQL database(A docker container) to retrieve a text string from a database called hello_world. I need to encrypt the database password before building the application within a NodeJS image. This image will then be pushed to the DockerHub repository.
It will then be downloaded and installed as a pod in the Minikube cluster via a Jenkins Pipeline in the dev namespace. There is a MySQL database pod already setup in the ‘dev’ namespace in which subsequent stages in the pipeline will test the retrieval of the text string from the database.
➜ nodejs-app git:(main) ✗ cat app.js
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const mysql = require('mysql');
// parse application/json
app.use(bodyParser.json());
//create database connection
const conn = mysql.createConnection({
host: 'dev-mysqldb',
user: 'mysqluser',
password: ‘xxxxxxxx’,
database: 'hello_world'
});
//connect to database
conn.connect((err) =>{
if(err) throw err;
console.log('Mysql Connected...');
});
//show all products
app.get('/',(req, res) => {
let sql = "SELECT * FROM messages";
let query = conn.query(sql, (err, results) => {
if(err) throw err;
// res.send(JSON.stringify({"status": 200, "error": null, "response": results}));
res.send(results);
});
});
//Server listening
app.listen(80,() =>{
console.log('Server started on port 80...');
});
I have 2 questions here.
How do I encrypt the database password in the above NodeJS application?
How do I make Kubernete pod decrypt the database password which was originally setup in the docker environment?
Thanks.
The simplest approach here is to use dotenv.
Usage:
Create a .env file in the root of your project:
S3_BUCKET="YOURS3BUCKET"
SECRET_KEY="YOURSECRETKEYGOESHERE"
As early as possible in your application, import and configure dotenv:
require('dotenv').config()
console.log(process.env) // remove this after you've confirmed it working
.. or using ES6?
import 'dotenv/config' // see https://github.com/motdotla/dotenv#how-do-i-use-dotenv-with-import
import express from 'express'
make sure to take a look at https://github.com/motdotla/dotenv#readme for more information.

React Native Access mysql db using express

I need to access my Data from my mysql Database using express, on my server the data is as a json, but when i try to access it i always get 'undefined' and my express server crash
the json i have on the server :
[{"idProjet":1,"nomProjet":"test","dateDebut":"2021-05-18T22:00:00.000Z","nomAuteur":"mathieu","prenomAuteur":"jean","organisme":"idmc"}]
fetching code :
let id = 'id :';
const [data, setData] = useState([]);
useEffect(() => {
fetch('http://localhost:3000/projets')
.then(response => {return response.json()})
.then((json => {console.log(json);setData(json);}))
.catch(error => console.error(error));
console.log(data);
}, []);
Route.js code :
const express = require('express');
const bodyParser = require('body-parser');
const mysql = require('mysql');
const connection = mysql.createPool({
host : 'localhost',
user : 'root',
password : '',
database : 'agora'
});
// Starting our app.
const app = express();
// Creating a GET route that returns data from the 'users' table.
app.get('/projets', function (req, res) {
// Connecting to the database.
connection.getConnection(function (err, connection) {
// Executing the MySQL query (select all data from the 'users' table).
connection.query('SELECT * FROM projet', function (error, results, fields) {
// If some error occurs, we throw an error.
if (error) throw error;
// Getting the 'response' from the database and sending it to our route. This is were the data is.
res.send(results)
});
});
});
// Starting our server.
app.listen(3000, () => {
console.log('Go to http://localhost:3000/projets so you can see the data.');
});
The most common problem for this type of behavior is that you are using react-native on an android emulator. Android Emulator is using an IP-address different from localhost on windows machine. For more information, check here the official documentation.
So you can forward your port on the same port used by the android emulator (10.0.2.2) or you can change the port to 80 so you won't have any problem
You can go check this answer here

How to integrate React Native with mySQL

I'm new in React Native and I'm trying to integrate my app with mySQL database located inside my hosting provider (digitalocean.com).
I've managed to get the data through nodejs and express but it's actually getting the data where my problem is.
Here how it goes:
I created a routes.js and inserted the following:
Note: the following credentials are real but is for pure testing and i don't mind sharing.
const express = require('express');
const bodyParser = require('body-parser');
const mysql = require('mysql');
const connection = mysql.createConnection({
host: '134.122.22.176',
user: 'yannb_9',
password: 'yannb_9',
database: 'tiomanGrow'
});
// Starting our app.
const app = express();
connection.connect((err) => {
if (err) {
console.log('Connection error message: ' + err.message);
return;
}
console.log('Connected!')
// Creating a GET route that returns data from the 'users' table.
app.get('/', function (req, res) {
// Connecting to the database.
// Executing the MySQL query (select all data from the 'users' table).
connection.query('SELECT * FROM farmers', function (error, results, fields) {
// If some error occurs, we throw an error.
if (error) throw error;
// Getting the 'response' from the database and sending it to our route. This is were the data is.
res.send(results)
});
});
});
// Starting our server.
app.listen(3000, () => {
console.log('Go to http://localhost:3000/farmers so you can see the data.');
});
Up until now everything's great! you can click on the http://localhost:3000/farmers and you'll see the data when you run the file.
Here's where I get stuck:
I was to display the data on my app and i have no idea how to possibly do that.
I did a few researches and saw a possible solution which didn't work. it actually gave me a "Network request failed"
import React from "react";
import { View, Text, StyleSheet, TextInput, TouchableOpacity } from "react-native";
import { HeaderImg } from '../components/HeaderImg';
import { Button } from '../components/Button';
export default class DB extends React.Component {
state = {
email: "",
password: "",
errorMessage: null
};
fetchData = async() => {
fetch('http://134.122.22.176:3000/farmers')
.then(response => response.json())
.then(users => console.dir(users))
.catch(error=> console.log(error))
}
render() {
return (
<View style={styles.container}>
<HeaderImg />
<View style={styles.errorMessage}>
{this.state.errorMessage && (
<Text style={styles.error}>{this.state.errorMessage}</Text>
)}
</View>
<Button
onPress={this.fetchData}
/>
</View>
);
}
}
const styles = StyleSheet.create({
});
Any suggestions?
The hostname for your MySQL database in your routes.js file is shown as 134.122.22.176. That's the database ip address. You cannot fetch from this IP address. MySQL databases do not respond to standard HTTP requests; they are not web servers.
Your Express app is running on localhost: http://localhost:3000/farmers - I am guessing you can surf to that URL in a web browser and see data, for example. If that Express app is running on your development computer, then you just need to find out the IP address (xx.xx.xx.xx) for that computer on your LAN, and use that in your fetch.
Starting from Android 9, google has decided to remove http client library from bootclasspath.
With Android 6.0, we removed support for the Apache HTTP client. Beginning with Android 9, that library is removed from the bootclasspath and is not available to apps by default.
For brief overview of the changes, visit.
In order to connect with http client, you have to add this line in your AndroidManifest.xml file:
<uses-library android:name="org.apache.http.legacy" android:required="false"/>
After that you should be able to connect with HTTP clients with your android Pie device.

Can't connect to mysql (express) with Node.js

Hello Stacksoverflowers,
I have a problem to connect my server.js file to Mysql via Express.
I've already insatlled mysql and express via npm.
when i run my server.js
The only thing it says in my console (MacOS default terminal) is:
"node server running now - using http://localhost:3000"
(I got no errors)
and my webpage also showing correct - "Node Server running - startpage" in the browser.
The problem is that they say nothing like "Connected to the MySQL server" or "Timeout: error messages" ?? (look at #3)
// Dan k
//#1
// My codes from server.js
const express = require('express');
const mysql = require('mysql');
const hostname = "localhost:";
const port = 3000;
//#2
// create connection to DB
const connection = mysql.createConnection({
host: "localhost",
user: 'root',
password: 'root',
port: 3000
});
//#3
// Connect to DB
connection.connect(function(err) {
if (!err) {
console.log('Connected to the MySQL server.');
}
else if (err)
{
return console.error('Timeout: ' + err.message);
}
});
// Routing with Express
const app = express();
//#4
// Startpage (root)
app.get('/', function(request, response){
response.send('Node Server running - startpage...');
response.end();
})
connection.end();
//#5
app.listen(port, (err) => {
if(err) throw err;
console.log("node server running now - using http://"+(hostname)+ .
(port)");
});
I got what is causing the issue. You are using the same port number 3000 to connect to your mysqlDB and at the same time using the same port to run your nodejs application.
This does throw an error but it takes a really long time to throw the error.
So the simple answer here is that the port that you are mentioning in your createConnection() method is incorrect and needs to be changed. This port should be port number on which your mysql DB is running. From the error it is clear that your mysql DB is not running on port 3306. You can check this post to figure out which port is your mysql DB running on. https://serverfault.com/questions/116100/how-to-check-what-port-mysql-is-running-on. Below is a reference for you. Please see the comments.
// create connection to DB
const connection = mysql.createConnection({
host: "localhost",
user: 'root',
password: 'root',
port: 3000 // You need to change this and put in the correct port number.
});