Sending data to Database in React.js web application - javascript

I'm creating a web application and I'm curious how to send data to MySQL database in it. I have a function that is invoked when user presses button, I want this function somehow to send data to the MySQL server. Does anyone know how to approach this problem? I tried npm MySQL module but it seems the connection doesn't work as it is client side. Is there any other way of doing it? I need an idea to get me started.
Regards

You will need a server that handles requests from your React app and updates the database accordingly. One way would be to use NodeJS, Express and node-mysql as a server:
var mysql = require('mysql');
var express = require('express');
var app = express();
// Set up connection to database.
var connection = mysql.createConnection({
host: 'localhost',
user: 'me',
password: 'secret',
database: 'my_db',
});
// Connect to database.
// connection.connect();
// Listen to POST requests to /users.
app.post('/users', function(req, res) {
// Get sent data.
var user = req.body;
// Do a MySQL query.
var query = connection.query('INSERT INTO users SET ?', user, function(err, result) {
// Neat!
});
res.end('Success');
});
app.listen(3000, function() {
console.log('Example app listening on port 3000!');
});
Then you can use fetch within a React component to do a POST request to the server, somewhat like this:
class Example extends React.Component {
constructor() {
super();
this.state = { user: {} };
this.onSubmit = this.handleSubmit.bind(this);
}
handleSubmit(e) {
e.preventDefault();
var self = this;
// On submit of the form, send a POST request with the data to the server.
fetch('/users', {
method: 'POST',
data: {
name: self.refs.name,
job: self.refs.job
}
})
.then(function(response) {
return response.json()
}).then(function(body) {
console.log(body);
});
}
render() {
return (
<form onSubmit={this.onSubmit}>
<input type="text" placeholder="Name" ref="name"/>
<input type="text" placeholder="Job" ref="job"/>
<input type="submit" />
</form>
);
}
}
Keep in mind that this is only one of infinite ways to achieve this.

It depends on how your application is organized, I will guess that you have a server that provides your React application code.
I would advise you to send the necessary information to your server (if there is any) using a module based on your preferences:
fetch built-in XHR api (https://developer.mozilla.org/en/docs/Web/API/Fetch_API)
request callback-based npm module (https://www.npmjs.com/package/request)
axios promise-based npm module (https://www.npmjs.com/package/axios)
If you are looking for a module/plugin doing all the work from client to database I don't know any and not sure there is because it is usually advised to use a proxy (a server to redirect but also to format or block requests between your client and the database).
Then, in your server you format the necessary information (if any) to be usable by your MySQL database, and then contact your MySQL database with the module of your choice, the first most popular module seems to be:
https://www.npmjs.com/package/mysql, but if you know another one or have other preferences go on. (For example with MongoDB we can use Mongoose to make requests easier)

Related

How to render page with a response data from node js to React js?

I am new to React with node
Now I want to send data from node js(backend) to React js with response data. Actually, my situation is after signup from Google authentication I want to send that data to a React js (frontend).
router.get(
'/auth/google/callback',
passportGoogle.authenticate('google', {
failureRedirect: '/',
}),
(req, res) => {
const nameFirst = req.user.profile._json.displayName;
const picture = req.user.profile._json.image.url;
const email = req.user.profile.emails[0].value;
const id = req.user.profile.id;
const user = new User({
user_token: id,
name: nameFirst,
email: email,
picture: picture,
provider: 'Google',
dateSent: Date.now(),
});
User.findOne({ email: email }, (err, docs) => {
if (docs != null) {
// already exist
} else {
// send data `user` with routing [routing to /signupnext,]
}
});
What you are describing composes an issue between computer systems: how to communicate.
Using JSON and REST, you can develop a REST endpoint as a node service.
All a REST endpoint is, is an HTTP Service Adress that behaves in a specific way.
What you need to do, is develop a REST Endpoint within your Node application and call that endpoint using your React application.
You cannot just "Send" the data to a client application, the application has to request it.
If you re-write your call so that your React.JS calls an endpoint, Node.JS authenticates and returns the result back to React, that should work for you.
More information on Node rest endpoints: https://www.codementor.io/olatundegaruba/nodejs-restful-apis-in-10-minutes-q0sgsfhbd

Multiple database switching dynamic in node-express

i have searched lot to get a solution to my problem. but didn't got it.
if anyone have the experience in such situations please help me.
i have created a application server in node express with MySQL a database.
and successfully create REST API endpoints which works successfully.
but our projects scaled up. a new client approaches so we need to serve those clients too.
those client may have 1k users.but the database schema is same.
solution 1: create a separate server and database for each client with different port no.
but i don't think this is good solution because if we have 100 client we can't maintain the code base.
solution 2: create a separate database for each client and switch database connection at run time.
but i don't understand how to implement solution 2. any suggestion highly appreciated.
if more than one client requesting same server how to know which database need to connect using the endpoint URL. i there any alternate way to tackle this situation.
my solution: create a middle ware to find out the which database is required and return the connection string.is it good idea.             
middleware. in below example i use JWT token which contain database name.
const dbHelper=new db();
class DbChooser {
constructor(){
this. db=
{
wesa:{
host: "xxx",
user: "xxxx",
password: "xxxxx",
database: "hdgh",
connectionLimit:10,
connectTimeout:30000,
multipleStatements:true,
charset:"utf8mb4"
},
svn:{
host: "x.x.x.x.",
user: "xxxx",
password: "xxx",
database: "xxx",
connectionLimit:10,
connectTimeout:30000,
multipleStatements:true,
charset:"utf8mb4"
}
};
}
async getConnectiontring(req,res,next){
//console.log(req.decoded);
let d=new DbChooser();
let con=d.db[req.decoded.userId];
console.log(mysql.createPool(con));
next();
}
}
module.exports=DbChooser;
You can create a config JSON. On every request, request header should have a client_id based on the client_id we can get the instance of the database connection.
your db config JSON
var dbconfig = {
'client1': {
databasename: '',
host: '',
password: '',
username: ''
},
'client2': {
databasename: '',
host: '',
password: '',
username: ''
}
}
You should declare a global object, to maintain the singleton db instances for every client.
global.dbinstances = {};
on every request, you are going to check whether the instance is already available in your global object or not. If it's available you can go continue to the next process, otherwise it creates a new instance.
app.use('*', function(req,res) {
let client_id = req.headers.client_id;
if(global.instance[client_id]) {
next();
} else {
const config = dbconfig[client_id];
connectoDb(config, client_id);
}
}
function connectoDb(config, client_id) {
//.. once it is connected
global.instance.push({client_id: con}); //con refers to the db connection instance.
}

pass the credentials of user to all views node.js

I'm trying to build an android application using node.js web services,the first interface allow the user to connect to a host using ip address,login and password, so he can get all the databases,i want to save the object credentials to use in all other routes,i tried express-session but it didnt worked.
Any solution?
app.post('/connect',function(req,res){
sess=req.session;
sess.user=req.body.user;
sess.password=req.body.password;
sess.server=req.body.server;
sess.database=req.body.database;
console.log(sess)
user = req.body.user;
password = req.body.password;
server = req.body.server;
database = req.body.database;
var config = {
user: user,
password: password,
server: server,
database: database
};
// connect to your database
sql.connect(config, function (err) {
if (err) {res.json({success: false, message: "error connexion to SQL Server"});
sql.close()}
else{
res.json({success: true, message: "connexion established to SQL Server"});
sql.close();
}
});
});
In your case the request make by http lib of android (or another) which is not a browse then express-session will not work. Your server must be like a API server, client(android) request login server response a token (api key or the same), in next request client push data embeded token and server side can credentials the request. I suggest read about JWT (Json Web Token) to do this.
This is easy if you are using express module in node application.
You basically create routes using express and can pass the required data to the appropriate routes and views as follows
router.get('/', function(req, res, next) {
res.render('category',
{
videodata: vd
});
});
Here while rendering the response, the data that is to be passed is also included. It's name is videodata and value is vd

Send data back to node.js server from front-end

I am new to Node.js and I'm trying to figure out for few days how to make a simple login-register feature for a website using Express.js with EJS template engine and MySql.
I have installed Node on my PC and I've used the Express-Generator to make a basic folder structure (views, routes, public folders).
I understand how I can pass variables from node to the front end using ejs but I don't know how to pass it back. I've tried watching some tutorials on the internet but nothing seems to make me see the logic. Where do I put the MySql code? How can I pass back the input values once the user clicks "SUBMIT"?
How says Jake, I suggest to use Sequelize for MySQL.
I will try to make a small steps for your start, and after you can study more about each process and tool.
1) Front-end (EJS);
<form id="login" action="/login" method="post">
<input name="username" type="text">
<input name="password" type="password">
<input type="submit">Ok</input>
</form>
Here, the form will request the route login. The route:
2) Route
module.exports = function (app){
var login = app.controllers.login;
app.get('/', login.index);
app.post('/login', login.login)
};
The route will call the login method in the controller called login.js.
3) Controller
module.exports = function(app) {
var sequelize = require('./../libs/pg_db_connect'); // resquest lib of connection to mysql/postgres
var LoginController = {
index: function(req, res) {
res.render('login/index');
},
login: function(req, res) {
var query = "SELECT * FROM users"; // query for valid login
sequelize.query(query, { type: sequelize.QueryTypes.SELECT}).then(function(user){
if (req.body.username == user[0].username && req.body.password === user[0].password ){
res.redirect("/home");
} else {
res.render("login/invalid_access");
}
});
}
};
return LoginController;
};
In this point, is exec the query for to valid the login and verify if user can be log in. Request method is the main point.
For response and send information to view, it used res.SOME_METHOD:
res.send();
res.end();
res.download();
res.json();
Plus: Sequelize MySQL connection.
In the express structure, it's localized in lib/my_db_connection.js:
var Sequelize = require('sequelize');
module.exports = new Sequelize('database_name', 'user', 'pass', {
host: 'localhost',
dialect: 'mysql',
pool: {
max: 10,
min: 0,
idle: 10000
},
});
I suggest before you code, read the necessary docs.
You're going to have to use some sort of AJAX library (or vanilla js ajax) to send the information to a http endpoint you set up in express. For simple stuff the jquery ajax methods will do just fine. You will likely are looking to make a POST request.
As for the MySql code, checkout Sequelize. Its a cool library for interacting with sql databases from express. Its similar to how mongoose works for mongo.

Socket IO 1.2 Query Parameters

I can't figure out how to retrieve query parameters on the server side for socket.io
1.2.1
Here's my client side code
var socket = io('http://localhost:3000/',{_query:"sid=" + $('#sid').attr('data-sid') + "&serial=" + $('#serial_tracker').text()});
and the server side:
io.use(function(socket,next){ //find out if user is logged in
var handshake = socket.request;
console.log(socket.request._query);
handshake.sid = handshake.query.sid;
}
socket.request._query is:
{ EIO: '3', transport: 'polling', t: '1419909065555-0' }
Does anyone know how query parameters work in socket io 1.2.1?
Thanks for any help and if you need any more information, just ask me.
When sending handshake query data to socket.io, use the following property name in the object:
{
query: 'token=12345'
}
I see above you used _query for a property name instead.
You should be able to access the query information at socket.request._query at that point. I'm not sure if there is a better way to get a hold of that data? I'm guessing yes, since they put an underscore in front of it, but I haven't found a better way yet.
Here's the full example of a connect query that is working for me (forgive the formatting, I'm copy/pasting this out of different node modules into an inline solution).
Server (using socket 1.2.1 nodejs):
var restify = require('restify');
var api = restify.createServer();
var socketio = require('socket.io');
var io = socketio.listen(api.server); // api is an instance of restify, listening on localhost:3000
io.use(function(socket, next) {
// socket.request._query.token is accessible here, for me, and will be '12345'
next();
});
api.listen(3000, function() {
console.log('%s listening at %s', api.name, api.url);
});
Client (chrome browser using the client library located at https://cdn.socket.io/socket.io-1.2.1.js):
var socket = io.connect('http://localhost:3000/', { query: 'token=12345' });

Categories

Resources