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

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

Related

React Native app connection to mysql - API for production

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

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.

React.js + Express: how to run SQL requests implying several databases?

I am currently working on the API of a React.js project. I have no trouble running SQL requests with databases on MySql servers using Express as long as the SQL request only implies a single database.
My problem: I now have to run an SQL request which implies using data from several databases and I do not know how to do it.
What I currently do in my server.js file to run SQL on a single database:
...
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const mysql = require('mysql');
...
let sql = "";
...
// *************************
// CLIENT & DB CONFIGURATION
// *************************
const app = express();
app.use(bodyParser.json()); // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true
}));
var server = app.listen(3001, "127.0.0.1", function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
});
app.use(cors());
const connection = mysql.createConnection({
host : 'myhost.fr',
user : 'someone',
password : 'aZefdt%',
database : 'SuiviTruc',
multipleStatements : true
});
connection.connect(function(err) {
if (err) throw err
console.log('You are now connected with SuiviTruc database...')
});
// **************
// Request sample
// **************
app.get('/SelectAffaire_',(req, res) => {
let sql=`SELECT * FROM t_Affaire_;`
connection.query(sql, (error, result)=> {
if (error) throw error;
res.send(result);
})
})
Thanks for your help!

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