How to connect ReactJS with Backend like Mysql - mysql

I am new to reactJS...
I am familiar with python-django.. now i wanna create backend for my react app.
used react for just front end purpose.. is their a way to communicate my react frontend with react own backend?
I am using MySQL Database.. is their any better way to create API in react Backend?
i knew this connection part alone,
var mysql_conn = require('mysql')
var connection = mysql_conn.createConnection({
host : 'localhost',
database : 'my_db'
});
connection.connect()
connection.query('SELECT _data AS solution', function (err, rows, fields) {
if (err) throw err
console.log('The solution is: ', rows[0].solution)
})
connection.end()
any suggestion ? shall i use any framework like expressJS with React?

Related

Connecting to a remote MySQL database from Stackblitz Node.js project

I have a Node.js Stackblitz project that I am trying to connect to a remote MySQL database. It is not possible to have a MySQL database within Stackblitz, hence trying the remote approach. However I get "Error: connect ETIMEDOUT" whenever I attempt a connection. Any help or pointers much appreciated.
I am using the code below. The remote database is accessible with the credentials I am using and returning data when used outside of Stackblitz. Is remote database access not possible with Stackblitz or am I missing something?
const express = require('express');
const mysql = require('mysql2/promise');
const app = express();
const port = 3010;
const path = require('path');
app.use(express.static('static'));
app.get('/', async function (req, res) {
try {
// create connection
const connection = await mysql.createConnection({
host: process.env.DB_HOST,
port: process.env.DB_PORT,
database: process.env.DB_DATABASE,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
});
// query database
const [rows, fields] = await connection.execute('SELECT * FROM `user`');
res.send({
rows,
fields,
});
} catch (err) {
console.log('err:', err);
}
});
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`);
});
For anyone looking for an explanation.
Currently a mysql database cannot reside in StackBlitz. Additionally, neither can it connect to an external mysql database on its own either.
You therefore required a backend API outside of StackBlitz to make the database calls, negating the reason for building the backend on StackBlitz in the first place (IMO). Therefore, the suggested setup currently would be a localhost backend API accessed from a frontend in StackBlitz via an ngrok secure address.
StackBlitz are working on getting basic server requests running in the future. So, watch this space.
I hope this answer helps save others time.

How to connect my react native expo project with MySQL? [duplicate]

I'm using React Native. I want to find the data I entered in React Native in the database. For example, in the database of the user name I entered, "select id from table where ('data I entered in react native')". I want to find the table with the user name and pull the user's id.
var name = this.state.username;
"select id from table where (name)"
I want to pull the id of the user name like this.
There is no direct connection between RN and Mysql. Use Node js for this.
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.');
});
Now, how do we get that data on our React Native App?
That's simple, we use the fetch function.
To do that, instead of using 'localhost:3000', you'll have to directly insert your PC's ip adress. If you use 'localhost', you're acessing your smartphone/emulator's localhost. And that's not what we want. Follow this example:
test(){
fetch('http://yourPCip:3000/users')
.then(response => response.json())
.then(users => console.warn(users))
}
You need to have a backend service/API in order to fetch data from database. try using Node, and write a simple backend since its JavaScript. You can execute sql queries on backend, retrive data from mySQL to your node server and then you can fetch data from the backend server to react-native using fetch method. (both your backend API and the device that running react native application should be running on the same network.)

Best practice to accessing mysql database by nodejs

Currently I'm running a node js backend with express to access the mysql database from the client. Now I'm refactoring my code to put the "fat" things from the client also to the nodejs backend.
My first idea is to keep the express route like:
ModuleA:
router.get('/getitem/:code',(req, res) => {
let sql = `SELECT * FROM xyz WHERE CODE = ${req.params.code}`;
let query = db.query(sql, (err, result) =>{
if(err == null){
console.log(result);
res.send(result);
}else{
console.log("Error by getting item from db: " + err);
throw err;
}
});
});
And access it via http request by a other module if needed:
function geodataByLocationcode(locationcode){
request({
method: 'GET',
url: "http://" + server_connection.host + ":" + server_connection.port + '/getitem/' + locationcode,
headers: {
"Content-Type": "application/json"
}
},function(error, response, body){
....
}
But is this the best method to do this?
Or would it be better to access the db in a more direct way
since the request now also comes from the backend?
You can find a good example how to use MySql and Node.js using native drivers (without any query builder like knex or ORM like bookshelf).
Dependencies:
expressjs 4.x
mysql2
expressjs 4.x
The core concepts are:
Have a separate file to handle database connection (https://github.com/Talento90/organization-api/blob/master/organizations-api/src/database.js)
Always use a connection pool
Separate the database logic from the API controllers (it makes them decoupled from database and easier to test)
If you are using the latest version of Node.js also shows you how to use async/await with express.js and mysql
Example: https://github.com/Talento90/organization-api/tree/master/organizations-api/src

using mysql in Electron

Im trying to use mysql in electron but i'm running into this error
TypeError: Invalid data, chunk must be a string or buffer, not object
at Socket.write (net.js:667)
at Protocol.<anonymous> (Connection.js:100)
with this code
var mysql = require('mysql');
var con = mysql.createConnection({
host: 'host address',
user: 'username',
password: 'pw',
database: 'db name',
});
con.connect(err => {
if(err) throw err
})
con.query('select * from BOOKS', (err2, result) => {
if(err2) {
throw err2;
}
console.log(result);
})
if i paste this into a test.js file and run it with node then it runs 100% fine without errors, so im not really sure where im going wrong here
So it turns it my issue had something to do with the fact that I was running Angular on electron. if I put that code inside my Angular code it would error out but if I put it in the index.html it would run fine.
So I just made a little proxy function in the index.html for connecting to the DB and making queries, then i'd jsut call it from inside the Angular app without a problem like window.mysqlQuery(queryString)

How I can write this code to work properly in nodejs

I have config.js in my nodejs project
var mysql = require('mysql');
var db_name = 'node';
var client = mysql.createClient({
user: 'root',
password: 'pass',
});
client.query('USE '+db_name);
I have used it as config file for the project. How I can use this code to call a mysql query.
I have this code in user.js
var global = require('./config.js');
this.CheckUserValid = function (login, pass) {
var sql = "SELECT * FROM `user` WHERE login = ? AND pass= ?";
global.client.query(sql, [login, pass], function selectResutl(err, results, fields) {
if (!err) return results;
else
throw err;
});
}
TypeError: Cannot call method 'query' of undefined
at Object.CheckUserValid (C:\wamp\www\Node\user.js:6:19)
Can someone help me to let me know how I can do this in better way.Actually I am using asp.net mvc in my past so I have tried it. Do someone tell me the better way to write code in nodejs.
When you require() a file/module, the result you get is whatever the module is exporting through the exports property. Anything else is encapsulated in the module and cannot be accessed from the outside. In your case, at the end of config.js you can add:
exports.client = client;
This way it will be accessible whenever you require() your config.js.
This way of creating modules is defined in the CommonJS spec:
http://commonjs.org/specs/modules/1.0/
http://wiki.commonjs.org/wiki/Modules/1.1
edit: and since commonjs.org seems to be down, here is another link with information about this type of module: http://dailyjs.com/2010/10/18/modules/