How to integrate React Native with mySQL - 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.

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

How can I retrieve data from mysql upon clicking on a button by react-native

I'm currently having an error on my code on retrieving MySQL data upon clicking a button.
Here is my 'route.js'.
const express = require('express');
const bodyParser = require('body-parser');
const mysql = require('mysql');
const connection = mysql.createPool({
host: 'localhost',
user: 'root',
password: 'password!',
database: 'mydb'
});
// Starting our app.
const app = express();
// Creating a GET route that returns data from the 'users' table.
app.get('/user', 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 user', 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/user so you can see the data.');
});
async function test(){
await fetch('http://mylocalpcIP:3000/user',{
method: 'POST', // Here you're saying that you want to make a POST request. Could be any method, like a GET, for example.
headers: '', // You can specify your requisition headers here. That line is optional.
body: { // Here's the fun part. Put your data here.
"name": this.state.name,
"age": this.state.age,
"phone_number": this.state.phone_number
}
})
.then(response => response.json())
.then(user => console.warn(user))
};
export {test};
Then, I've called test function as such:
import React from 'react';
import { View, Text, StyleSheet, TouchableOpacity } from 'react-native';
import {test} from "./db/routes.js";
const MyScreen = ( {navigation} ) => {
return (
<View style={styles.container2}>
<TouchableOpacity
style = {[styles.mid_box, styles.pbox]}
onPress={() =>{
test();
navigation.navigate("Dating_to_Profiles")
}}>
<View>
<Text style = {styles.textstyle}>1st Introduced Profile</Text>
</View>
</TouchableOpacity>
And I'm getting this scary message when I reload the emulated Android.
Well.. It's very likely that I've messed up somewhere since I don't know much about anything yet.
I'd appreciate a lot if someone can teach me how to retrieve data via POST method.
Thanks a lot in advance!
Express is a NodeJS framework and thus obviously not compatible with react-native.
If you wanted to create an API where your data that was queried from MYSQL is served as JSON so it can be fetched by your app, I recommend this tutorial for you.

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 can I Fetch and display Mysql data into ReactJS front end with Node JS as backend?

Trying to figure out on how to fetch data from mysql and display it in ReactJS. I'm using NodeJS on the backend along with express. I tried a code snippet found on the internet but it doesn't work as it is expected.
Here's what i get when i run the react app.
TypeError: http.ServerResponse is undefined
My NodeJS code
//require mysql, http and express
//const connection = createConnection({with host, user, pass, db});
const app = express();
app.get('/posts', function(request, result){
connection.connect();
connection.query("SELECT * FROM 'some_table';", function(err, results, fields){
if(err) throw err;
result.send(results);
})
connection.end();
})
app.listen(3000);
My React code
class Display extends React.Component{
constructor(props){
super(props);
this.state={ posts : [] };
fetch('http://localhost:3000/posts/')
.then(response =>{
response.json();
})
.then(posts => {
this.setState({posts})
})
.then( (err) => {
console.log(err);
})
}
render(){
return(
<div>
<ul>
{this.state.posts.map( post =>
<p>
<li>Some Text_1: {post.db_col_1}</li>
<li>Some Text_2: {post.db_col_2}</li>
<li>Some Text_3: {post.db_col_3}</li>
</p>
)}
</ul>
</div>
)
}
}
export default Display;
Your code needs some error handling and CORS policy. So I would recommend to you do;
Make sure your backend is up and running
You need to check your ports on backend.
Make sure database up and running
You need to check your connection is there for your database. No need to connect to your database each time when you make request. So better to connect once.
Try your API result via Postman or any other tool
You need to make sure your backend is reachable via any other client app. You can also open your browser and test your API with opening the link in browser 'http://localhost:3000/posts'
Activate CORS policy for your backend.
SPA needs CORS policy to make a request to the backend. You can use cors npm library for that or you can create your own rules.
Use a fetch library
You can use fetch but it is not supported by all browsers. It would be nice to Axios or any other request tool on your client code.
const cors = require('cors')
const app = express();
const mysql = require('mysql');
const connection = mysql.createConnection({
host: "localhost",
user: "yourusername",
password: "yourpassword"
});
connection.connect(function(err) {
if (err) throw err;
console.log("Connected!");
});
app.use(cors());
app.get('/posts', (req, res) => {
connection.query("SELECT * FROM 'some_table';", (err, results, fields) => {
if(err) throw err;
res.send(results);
});
});
app.listen(3000, (error) => {
if (err) throw err;
console.log(`App listening on port ${port}!`)
});
According to the React documentation, The constructor for a React component is called before it is mounted. It also states the following:
Avoid introducing any side-effects or subscriptions in the constructor. For those use cases, use componentDidMount() instead.
You should do API calls in componentDidMount. According to React documentation:
If you need to load data from a remote endpoint, componentDidMount is a good place to instantiate the network request.
Your code should look like the following:
import React from "react";
class Display extends React.Component {
constructor(props) {
super(props);
this.state = { posts: [] };
}
componentDidMount() {
fetch("http://localhost:3000/posts/")
.then(response => {
response.json();
})
.then(posts => {
this.setState({ posts });
})
.then(err => {
console.log(err);
});
}
render() {
return (
<div>
<ul>
{this.state.posts.map(post => (
<p>
<li>Some Text_1: {post.db_col_1}</li>
<li>Some Text_2: {post.db_col_2}</li>
<li>Some Text_3: {post.db_col_3}</li>
</p>
))}
</ul>
</div>
);
}
}
export default Display;
The above snippet will work provided your back-end Node.js application is returning the proper data.
Taking up the other answer that mentions password: "yourpassword", check that you have a password set for the user that you use to connect to the database.
I had the issue with PostgreSQl, but that could be the same thing somewhere else: the fresh install does not automatically set a password for the super user, nor is a password set automatically for any other user that you create from the super user login.
The errors shown do not hint at the issue, see for example TypeError: Cannot read property 'rows' of undefined which seems to solve an error of the "rows" in the code, but in reality is just an error of a missing password.
If there is no password set, you can try as much as you want, you will not get access to the backend. In PostgreSQL, I had to follow FATAL: password authentication failed for user "postgres" (postgresql 11 with pgAdmin 4).

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