REACT NATIVE Retrieving data from localhost MySQL database - mysql

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

Related

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.

Testing an AWS Lambda function

I need to create a lambda function to act as the middleman between a mobile Java app and an AWS RDS MySQL database. The idea is to submit queries from the mobile app and then send them off to the lambda function, which will then return the query. I have a basic MySQL query set up in my AWS lambda:
var mysql = require('mysql');
var config = require('./config.json');
var pool = mysql.createPool({
host : config.dbhost,
user : config.dbuser,
password : config.dbpassword,
database : config.dbname
});
exports.handler = (event, context, callback) -> {
context.callbackWaitsForEmptyEventLoop = false;
pool.getConnection(function(err, connection) {
if (err) throw err; // not connected!
// Use the connection
connection.query('select Album from record', function (error, results, fields) {
// When done with the connection, release it.
connection.release();
// Handle error after the release.
if (error) callback(error);
else callback(null, results[0].Album);
// Don't use the connection here, it has been returned to the pool.
});
});
};
And all that I am currently trying to do is get this code to run and output what the query will return. I've seen tutorials where people seem to just click test and have the code run, but it keeps asking me to create a test, and I'm not sure what exactly I would need to do to test this function.
EDIT: I realized I was missing a small change in my lambda uploaded code, but I am now getting an error on line 10 saying there is an unexpected token >.
I'm not sure what's wrong here, as the tutorial I watched seems to have the same exact thing.
Since you're not passing in any parameters through the context, you can just create a test with the defaults or an empty object {}, and click Test in the console. It will invoke your Lambda function as if it had been called from your mobile app, and you can debug from there.

How to use Mysql and MongoDB on same NodeJs server?

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

How to configure custom database Mysql in Auth0 Connection?

I'm using auth0 as my authentification services into my project. I really love it, but I have a problem when using custom database(MySql), I sure that I have configured the db.connection parameter to my remote shared hosting database in Plesk. It always show : "[Error] Script execution did not complete within 20 seconds. Are you calling the callback function?", When I trying to run "Create" script.
here the script :
function create (user, callback) {
var mysql = require('mysql');
var connection = mysql.createConnection({
host : '192.168.23.16',
user : 'user',
password : 'pass',
port : '3306',
database : 'dbname' });
connection.connect();
var query = "INSERT INTO users SET ?";
var insert = {
password: bcrypt.hashSync(user.password, 10),
email: user.email
};
connection.query(query, insert, function (err, results) {
if (err) return callback(err);
if (results.length === 0) return callback();
callback(null);
});
}
What should I'm doing right now to solve this problem? I'm new to this
Thanks..
Regards,
fxbayuanggara
You're trying to connect to a local IP address (192.168.23.16), which will always fail since database scripts and rules are executed from Auth0's servers. You'll need to make your MySQL server accessible from Auth0's IP addresses, which at the time of writing are the following:
US domains: 138.91.154.99, 54.221.228.15, 54.183.64.135, 54.67.77.38, 54.67.15.170, 54.183.204.205, 54.173.21.107, 54.85.173.28
EU domains: 52.28.56.226, 52.28.45.240, 52.16.224.164, 52.16.193.66

How to use express.js with mysql and express-myconnection?

I am using Express 4.9.0 and express-generator. Executed this command:
express --hbs projectname
Installed following modules with NPM:
mysql
express-myconnection
I want to make todo application. I have created separate file under routes/todo.js and created get/post routes for creating todos in that file using router.get and router.post.
i have following code in app.js:
// mysql connection
var connection = require('express-myconnection');
var mysql = require('mysql');
app.use(
connection(mysql, {
host : config.db.host,
user : config.db.user,
password : config.db.password,
database : config.db.database,
debug : false //set true if you wanna see debug logger
}, 'request')
);
// end of mysql connection
Where should i place mysql config and connection code? Inside todo.js? I still don't get concept of organisation file structure and where to place database queries.
I don't know if you eventually found the answer, but I thought it might help out others who accidentally stumbled on your question:
After you've setup like mentioned above, you can call the connection from the request object using the getConnection method like this:
exports.index = function(req, res) {
req.getConnection(function (err, connection) {
connection.query('select * from table_name', function(err, rows, fields){
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.jsonp(rows);
}
});
});
};
This should print out a json with the content of your table all nice an pretty.
Hope this comes in handy.