React Native app connection to mysql - API for production - mysql

I have created my first app using expo and react native.
My backend is written in node.js (with express and axios) and connected to mysql database. I will be using get, post and put.
What I don't understand is how I move from a development environment to a production environment. In order to connect my API to an external server how do I go about setting up a baseURL which would replace my IP address and port in the below example?
Axios.post("http://53.183.245.150/:19056/location", body).then((response) => {
console.log(response);
}).catch(err => console.log(err))
I have searched online and all examples which they create an API only include running off the local server rather than creating a production app and setting up a remote server.
I would like to link the mobile app to my existing production DB (using mysql) and running off AWS. This DB is connected to my website which is up and running. My backend for my website is written in PHP.
Thank you for any guidance!
I have attached an example of my server as well.
const express = require('express');
const app = express();
const mysql = require('mysql');
const cors = require('cors');
app.use(cors());
app.use(express.json());
const db = mysql.createConnection({
user:'root',
host:'my ip address here',
password:'',
database: 'myDB',
});
app.post('/login', (req, res) => {
const user = req.body.user;
const password = req.body.password;
db.query('SELECT * FROM users WHERE uidUsers = ? AND pwdUsers = ?', [user, password], (error, rows, fields) => {
if (error) console.log(error);
if (rows.length > 0) {
res.send(rows);
} else {
res.send(rows);
}
});
})
app.get('/trips', (req, res) => {
const driver = req.query.driver;
const companyId = req.query.companyId;
const status1 = req.query.status1;
db.query('SELECT * FROM trips WHERE driver = ? AND company_id = ? AND status_1 = ?', [driver, companyId, status1], (error, rows, fields) => {
if(error) console.log(error);
else{
console.log(driver)
res.send(rows);
}
})
});
const PORT = process.env.PORT || 19056;
app.listen(PORT, () => {
console.log(`Listening on port ${PORT}`);
})

Related

Getting "Cannot GET /isFavorite" on my Node.js app hosted on DigitalOcean

Why am I getting the following error? I have a small Nodejs app hosted on DigitalOcean. I am getting the following error "Cannot GET /isFavorite" when I run the following post command in Postman: "http://octopus-app-s7q5v.ondigitalocean.app:8080/isFavorite" with body JSON parameters of:
{
"userid": "101",
"petid": "1"
}
The route I have for the app is an app.post("/isFavorite") and not an app.get. It is connected to a MySQL database which is also hosted on DigitalOcean. I have included a small version of the code for the app below. Why would I be getting this error? When I add an app.get("/") and return a response of "Hello" that works. It runs locally. I have configured all the environment variables in DigitalOcean settings. I have the "ca-certificate.crt" in the root of my Nodejs app. DigitalOcean app platform says it builds and deploys fine on the server.
Also, regarding the console.logs I have added to the code, where are they stored? I can see the one which starts the webserver and listens but not any of the others. The app is listening on port 8080 and has an IP address of 0.0.0.0.
const bodyParser = require("body-parser");
const querystring = require('querystring');
const router = express.Router();
const app = express();
app.use("/", router);
const mysql = require('mysql');
const fs = require('fs');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(express.json());
app.post("/isFavorite", (req, res) => {
try {
console.debug("isFavorite Start");
const conn = mysql.createConnection({
host: process.env.DBHOST,
port: process.env.DBPORT,
user: process.env.DBUSER,
database: process.env.DBNAME,
password: process.env.DBPASSWORD
});
console.log("isFavorite logged on to db");
let selectQuery = 'SELECT COUNT(*) c FROM Favorites WHERE userID = ? AND petID = ?';
let query = mysql.format(selectQuery,[req.body.userid, req.body.petid]);
conn.query(query,(err, response, fields) => {
if(err) {
console.log(err);
res.status(500).send("Error querying database.");
return;
}
// rows added
console.log("isFavorite");
console.log(response.length);
if (response.length > 0) {
console.log(JSON.stringify(response));
res.status(200).json({IsFavorite: response[0].c >= 1});
} else {
res.status(200).json({IsFavorite: false});
}
});
} catch (err) {
next(err);
}
});
let PORT = process.env.PORT || 3000;
let IP = process.env.IP || '127.0.0.1';
app.listen(PORT, IP, () => {
console.log('Server is running at port ' + PORT + ' and IP = ' + IP);
});

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 make a node.js api and deploy it to heroku (postgresql or mySQL database)

I am working on rest api with node.js and express that connects to the client side I have found a tutorial here https://www.taniarascia.com/node-express-postgresql-heroku/ and everything works fine but it will not deploy to heroku and I do not know why because everything works fine when I run it on localhost. Why is this happening?
Here is my code
index.js
const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const {pool} = require("./config");
const { get } = require("mongoose");
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(cors());
const getBooks = (req, res) => {
pool.query('SELECT * FROM books', (err, results) => {
if(err){
throw err;
}
res.status(200).json(results.rows);
});
}
const addBook = (req, res) => {
const {author, title} = req.body;
pool.query(
'INSERT INTO books (author, title) VALUES ($1, $2)',
[author, title],
(err) => {
if(err){
throw err;
}
res.status(201).json({status: "success", message: "Book added."});
},
)
}
app.route("/books").get(getBooks).post(addBook);
app.listen(process.env.PORT || 8000, () => {
console.log(`Server listening`);
})
config.js
require("dotenv").config();
const {Pool} = require("pg");
const isProduction = process.env.NODE_ENV === "production";
const connectionString = `postgresql://${process.env.DB_USER}:${process.env.DB_PASSWORD}#${process.env.DB_HOST}:${process.env.DB_PORT}/${process.env.DB_DATABASE}`;
const pool = new Pool({
connectionString: isProduction ? process.env.DATABASE_URL : connectionString,
ssl: isProduction,
});
module.exports = {pool};
init.sql
CREATE TABLE books (
ID SERIAL PRIMARY KEY,
author VARCHAR(255) NOT NULL,
title VARCHAR(255) NOT NULL
);
INSERT INTO books (author, title)
VALUES ('J.K. Rowling', 'Harry Potter');
I'd have a look at this, if your app works fine locally but not on heroku it's probably a deployment issue:
https://devcenter.heroku.com/articles/getting-started-with-nodejs
Specifically, l think you probably need a Procfile which is like an extra file that Heroku needs to deploy. Assuming you got set up using the cli (https://devcenter.heroku.com/categories/command-line) you can get more detail on how your app is failing by getting the logs using 'heroku logs -t' inside the folder you deployed from.

I am getting PROTOCOL_ENQUEUE_AFTER_FATAL_ERROR

I am not able to connect to MYSQL with nodejs even though I can access MySQL with Workbench. I am getting the PROTOCOL_ENQUEUE_AFTER_FATAL_ERROR error and I am not able to determine anything wrong with the code here. How should I go about it? Many thanks in advance.
const express = require('express')
const cors = require('cors')
const mysql = require('mysql')
const app = express()
const SELECT_ALL_PRODUCT_QUERY = 'SELECT * FROM products';
const connection = mysql.createConnection({
host:'localhost',
user:'root',
password:'password',
database:'reactdb'
})
app.use(cors())
app.get('/', (req, res) => {
res.send('hello world from the product server')
})
app.get('/productlist', (req, res) => {
connection.query(SELECT_ALL_PRODUCT_QUERY, (err, results) => {
if(err){
return res.send(err)
}
else {
return res.json({
data: results
})
}
})
})
app.listen(4000, () => {
console.log('Product server is listening to port 4000')
})
I managed to solve the connection error by creating a new MySQL user instead of using the root user. Thanks

How to resolve 502 Mysql query error on Netlify (Express server)

I have a React app + Express server deployed on netlify here. I have a simple api endpoint that queries my MySql DB on AWS.
When I make the api request I am given a "Failed to load resource: the server responded with a status of 502".
If I just return a simple
res.send("simple response")
then everything works fine and I get the response on the client. Could someone point me in the right direction on what I should be looking for?
I've tried to disable the skip_name_resolve parameter on my db to see if the hostname mattered, opening up access to all ports / ip's on the aws security group, look up common examples of express + mysql server implementations, lookup the netlify function docs, and using async await in the server.
// client.jsx
useEffect( () => {
fetch("/.netlify/functions/server/api/getSalesData")
.then(res => res.json())
.then(res => console.log(res));
// server.js
const express = require("express");
const bodyParser = require("body-parser");
const serverless = require('serverless-http');
const mysql = require("mysql");
const db = mysql.createConnection({ ... });
db.connect(function(err) {
if (err) throw err;
console.log('You are now connected...')
});
const app = express();
const router = express.Router();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
router.get("/api/getSalesData", (req, res) => {
// res.send({ express: "Hello from express" });
db.query("SELECT * FROM Sales LIMIT 5", (err, rows) => {
if (err) throw err;
res.send(rows);
});
});
app.use('/.netlify/functions/server', router);
module.exports = app;
module.exports.handler = serverless(app);