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
Related
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}`);
})
I am very new to programming so I do apologize if this is a really simple question.
So, I have been trying to connect my React Native application to the MySQL Database using Node and Express server, but I keep on getting the following error (I have checked other stackoverflow questions as well, but nothing has helped):
Error
I have checked my host name and port number multiple times and the all the information seems to be correct. I am not sure what is wrong with the following code:
var express = require("express");
var app = express();
var mysql = require("mysql");
var bodyParser = require("body-parser");
const { application } = require("express");
app.use(bodyParser.json({ type: "application/json" }));
app.use(bodyParser.urlencoded({ extended: true }));
var connection = mysql.createConnection({
host: '127.0.0.1', // Your connection adress (localhost).
port: "3306",
user: "root", // Your database's username.
password: "", // Your database's password.
database: "birthdays", // Your database's name.
});
connection.connect(function (error) {
if (error) console.log(error);
else console.log("connected");
});
// Starting our server.
app.listen(4547, () => {
console.log("Go to http://localhost:4547/dinners so you can see the data.");
});
app.get("/users", function (req, res) {
con.query("select * from users", function (error, rows, fields) {
if (error) console.log(error);
else {
console.log(rows);
res.send(rows);
}
});
});
I run this code by typing "node fileName.js" in the terminal.
I don't know if this is helpful, but I have also connected by MySQL database to MySQL Workbench.
Any help is appreciated!
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 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);
I was trying out fetching the information from MySQL 8.0 table into Node JS using Express. But I am constantly getting the error ER_NOT_SUPPORTED_AUTH_MODE. I tried many things such as:
Changing the authentication method for an individual user (and used multiple different users) - changed it from SHA 256 to Caching 256 and to default one (mysql_native_password) neither of them works.
Changing my Node js code: instead of using the single connection which was giving me the error - PROTOCOL_ENQUEUE_AFTER_FATAL_ERROR, I changed it to pool of connection but still getting the error ER_NOT_SUPPORTED_AUTH_METHOD.
I found out that MySQL Server uses SHA 256 password private key and public key, but I don't know how to implement it or use it in Node. js.
My database table: react_test
product_id | product_name | product_price
1 | abc | 10
Here is my Node.js code:
const express = require('express');
const cors = require('cors');
const mysql = require('mysql');
const app = express();
const SELECT_ALL_QUERY = 'SELECT * FROM project.react_test';
const connection = mysql.createConnection({
host:'localhost',
user:'avd',
password:'password',
database:'project',
insecureAuth : true
});
const pool = mysql.createPool({
host : 'localhost',
user : 'avd',
password : 'password',
authentication_string : 'root',
insecureAuth : true
});
//var pool = mysql.createPool(connection);
connection.connect(err => {
if(err) {
return err;
}
})
console.log(connection);
app.use(cors());
app.get('/', (req,res) => {
res.send('hello from product server')
});
app.get('/hola', (req,res) => {
res.send('hola')
});
app.get('/hotels_info', (req,res) => {
connection.query(SELECT_ALL_QUERY, (err, results) => {
if(err){
return res.send(err)
} else {
return res.json({
data: results
})
}
});
});
app.listen(4000, () => {
console.log('Product server listining port 4000');
});
Error when using single connection: {"code":"PROTOCOL_ENQUEUE_AFTER_FATAL_ERROR","fatal":false}
Error when using pool of connection:
{"code":"ER_NOT_SUPPORTED_AUTH_MODE","errno":1251,"sqlMessage":"Client does not support authentication protocol requested by server; consider upgrading MySQL client","sqlState":"08004","fatal":true}
I dont know what to do further! Please guide me! Thank you in advance!