I have build a Todo App with create-react-app. The store I'm using is based on Local Storage(JS attribute of object window). Now I created a MySQL databases and want to connect to that database, so the state will show the values from database, and will be updated through actions.
I've tried to connect to db and output values through 'node' console using db.js. It works.
const mysql = require('mysql');
const con = mysql.createConnection({
host: "localhost",
user: "root",
password: "root",
database: 'root'
});
con.connect(function(err) {
if (err) throw err;
con.query("SELECT * FROM tasks", function (err, result, fields) {
if (err) throw err;
console.log(result);
});
});
Is it possible to connect the state of app to database using this script?
You can't connect them directly.
JavaScript running in a web browser cannot speak the MySQL protocol (nor can it make raw network connections that would be needed to write an implementation in JS).
Instead, create a web service (in the programming language of your choice, which could be JavaScript running on Node.js (e.g. the code you have already + Express.js + some glue)) and use Ajax to communicate with it.
The general solution for a question like this is the following framework:
Back-end (Node.js, Express, Database connection including authorization)
Front-end (React(, Redux to manage state))
If you then launch the React app, it should populate its state based on data retrieved from the database, which is a process to which you can add authorization (make retrievable data depend on the role/status of the user).
In the back-end you can define functions that take in a certain subset of parameters, which performs database actions, to which you can add business rules for your application. The React app then just sends HTTP requests to the Express server, which handles everything that needs verification and authorization before even touching the data.
If you search the internet for any configuration of a fullstack architecture using React and MySQL, you'll find similar results to what I mentioned.
Related
I'm unsure of how to apply the MVC architecture to my node web app, in specific separating the model from the controller.
The current structure has the views separated properly (all my .ejs files) and then I guess that my app.js is like the controller as it contains all the routes to respond to http requests. The routes are then handled in a queries.js file which is where I query my database using node-postgres (most of the views rendered are either displaying information from the database or displaying forms so the user can insert data to the database). Should I be doing this differently, or more specifically should I try to create a model that contains raw data from the database and have the route handlers manipulate this data instead of directly querying the database (not sure how I would handle inserting into the database then...)? I'm just concerned that the current way I have structured my web app will make it difficult to manage as it grows and difficult for other to understand and add on to.
Here is an example of how the web app is currently structured: Say a user clicks a button to display all the active orders, my app.js file would look something like this
const db = require('./queries')
app.get('/activeorders', db.getActiveOrders)
My queries.js file would then handle this route like so:
const Pool = require('pg').Pool
const pool = new Pool({
user: process.env.USER,
host: process.env.HOST,
database: process.env.DB,
password: process.env.PASSWORD,
port: process.env.PORT,
})
const getActiveOrders = (request, response) => {
const queryOrders = 'SELECT * FROM orders WHERE complete=0 ORDER BY date_rec DESC;';
pool.query(queryOrders, (error, results) => {
if(error) {
throw error
}
var ordersObj = results.rows;
response.render('pages/activeorders', {
ordersObj: ordersObj
})
})
}
module.exports = {
getActiveOrders,
}
As can be seen in the handler the database is queried and stores the results in an object that is then passed to the activeorders.ejs file when rendered.
Maybe using a middleware allowing you to make an API from a Postgresql database.
Any change made on the databases will be propagated and available to you API. It will also let a lot of modularity to possible filters/ select ...
And for complex queries DBA will be able to develop stored procs available to everyone by API. That is the Model layer. Only SQL exposed through a middleware.
Controller will be how you made you API calls and data transformations if needed to refresh data based in you View
Abstracting the model layer with a middleware definitely a huge economy on time.
For postgres majors options : postgres & pgrest
In MVC pattern we split each part of the application because this approach to software development for complex needs by connecting the implementation to an evolving model
I suggest you visit sample-mvc-express-postgres to understand structure code
If you are interested in design pattern, visit https://dev.to/salah856/implementing-domain-driven-design-part-i-5a72, This link explains how to use DDD in your application and show how to design each layer of the application
Set app.js as root file and create a controller and a model folder. Define all models in model folder, while in controller first import model files handlers and create all APIs or queries function. Then in the root app.js file import controller functions handler and run it.
I'm having a hard time understanding how to connect to the MongoDB Atlas Cluster from my react-native app. What I'm trying to do is basically take my data from my component login page (userName and password) and connect to the Atlas Cluster db to see if the data is there.
Im using React Native and use Expo to create the app. My login page opens up and I put in the data.
I want to take that data and then use the following code (from the Atlas Site Connection String) to connect and check.
const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb+srv://<userName>:<password>#testcluster1-dbdq3.mongodb.net/test?retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true });
client.connect(err => {
const collection = client.db("test").collection("devices");
// perform actions on the collection object
client.close();
});
Since react-native establishes a server, do I need to involve Express? Im new to this so I'm still trying to figure out what packages to utilize. Should I also install mongoose or mongoDB or both (from NPM). Im trying to wrap my head around how this works from a basic perspective and the packages required.
I want to perform a check against my userID and PW from my login page to the DB to see if the user exists. If the user doesnt, then I'll have them fill out some info and register which means writing a new user to my db.
So basically, I need to understand the code logic for:
Connecting to the db through my app and when to perform this
connection (when app loads or each time the login button is clicked)
Take data from my userName and password and search the atlas db to
see if the user exists. If so, then the next page loads.
If username and password doesn't exist, then I write the new user
and password to the db.
Thanks
I think you should rewrite the code following the format suggested by mongodb here:
https://mongodb.github.io/node-mongodb-native/api-articles/nodekoarticle1.html
So essentially:
const MongoClient = require('mongodb').MongoClient;
//make sure to check connection string is correct here, since this depends on the whether you are running standalone, replica, sharded cluster
const uri = "mongodb+srv://<userName>:<password>#testcluster1-dbdq3.mongodb.net/test?retryWrites=true&w=majority";
MongoClient.connect(uri, { useNewUrlParser: true }, function(err, client) {
if (err) {
//error
} else {
var collection = client.db('test').collection('devices');
//client.close() should be called after you are done performing actions such as collection.update, etc.
}
});
you can use any npm package with Expo if it works with RN (React Native), but you may need to detach in order to do so. Any npm packages which include native iOS or Android code will not work with Expo out of the box, unfortunately. Because MongoDB NPM package just mentioned the Node.js in thier docs, this doesn't mean that it will work on React Native. That's why MongoDB made this page about JUST React Native https://docs.mongodb.com/realm/tutorial/react-native/
You may need to use Realm Package to connect to MongoDB with React Native.
I'm trying to connect and request queries from my database, but I wanna do it with JavaScript (or jQuery).
I'm trying this:
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "myUser",
password: "myPassword",
database: "mydb"
});
function GetSqlResult (sql_query) {
con.connect(function(err) {
if (err) throw err;
//Select all customers and return the result object:
con.query(sql_query, function (err, result, fields) {
if (err) throw err;
return result;
});
});
};
But I get this error:
Uncaught ReferenceError: require is not defined
I've tried using using the module "require.js" from this website http://requirejs.org/docs/release/2.2.0/minified/require.js
I still got the same error.
I want a solution for this error (if it exists), not an alternative.
I know that connecting to a database from JavaScript isn't very safe, but I really wanna do it, so I would love for someone to help me, please.
Thank you
What you are trying to do without knowing it, is build a RESTful API. In web architecture, you have your front end code (browser javascript) which makes HTTP requests to a backend. That backend will connect to the database and run queries. Even if you wanted to do this from browser javascript, your browser wouldn't let you. I would recommend you write a REST Api using NodeJS, and have your browser javascript make HTTP requests to that backend. Hope this helps.
NodeJS is not jquery, nodeJs it runs on a backend web server.
you can use Meteor for connecting to database from the client side.
I have created simple react app using 'create-react-app'. This app contains form, validation and bootstrap things. Nothing fancy yet works like a charm.
I have also signed up to mongo to get a free cluster so I can send over some data to. So I have this URL:
mongodb+srv://matt:passwprd#cluster0-jlasm.mongodb.net/test
Now, all I want to do is to send JSON data from the form to mongo but I don't know how.
When I am following tutorials and installing MongoDB, mongoose or whatever packages and adding basic setup for future CRUD operations:
var MongoClient = require('mongodb').MongoClient
, assert = require('assert');
// Connection URL
var url = 'mongodb+srv://mattOsuch:brainhub123#cluster0-jlasm.mongodb.net/test';
// Use connect method to connect to the server
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
console.log("Connected successfully to server");
db.close();
});
The entire application crashes:
./node_modules/mongodb-core/lib/uri_parser.js
Module not found: Can't resolve 'dns' in 'C:\Users\Mateusz\Desktop\brainhub\node_modules\mongodb-core\lib'
I used to send data using jQuery or mysql_query in PHP but I can't overcome this problem. In other words I want to achieve functionality like presented in this video: https://www.youtube.com/watch?v=Jsqz5op4fH8 So as I said, simple data update.
My suspicion is that react-scripts server listener has some sort of conflict with mongo but I am not sure.
Please help me because I am loosing my nerves.
You are using node.js so start server app try using express routing here is a link to a tutorial https://zellwk.com/blog/crud-express-mongodb or https://codeburst.io/hitchhikers-guide-to-back-end-development-with-examples-3f97c70e0073 or try doing a google search(node.js mongodb and express).
Then when returning a request from server send the data required then use your react client to handle the data recived
Hope it works!
handleSubmit(){
let databody = {
"name": this.state.name,
// Remaining form Data
}
return fetch('mongodb+srv://mattOsuch:brainhub123#cluster0-jlasm.mongodb.net/test', {
method: 'POST',
body: JSON.stringify(databody),
headers: {
'Content-Type': 'application/json'
},
})
.then(res => res.json())
.then(data => console.log(data));
}
render(){
return (
<div>
<form onSubmit={this.handleSubmit}>
// Form Fields
<input type="submit" value="Save" />
</form>
</div>
);
}
To connect to MongoDb in javascript, you must use a node.js server.
It is therefore impossible to directly connect your React application to your MongoDb cluster.
For more information, visit the official MongoDb documentation
First you need to create a React.js on the frontend and then node.js on the backend web application.
Then, you need to connect your mongodb collection to your Node.js server.
Then you can send your form data to your node.js server and your node.js server will send your form data to your mongodb collection.
Making a full-stack React-NodeJS-MongoDB web application can be a little challenging, if you do not know NodeJS. So you might first start with EJS-NodeJS-MongoDB web application. But in any case, here are links for your question:
https://www.youtube.com/watch?v=3isCTSUdXaQ&t=2248s
https://www.youtube.com/watch?v=Oa0pMn0tvU4&t=1316s
I have done some Angular 2 for the first time and after the html and css I now am stuck at the DB connection.
Here is what I am working with:
app.component.ts (Loads the templateURL)
overview.component.html (Is the template, 90% html 10% Modal)
db_basic.db (The DB File)
sql.js (This can get Values of the db if you do node sql.js)
Here the sql.js file to show how I can connect to the DB.
var sqlite3 = require('sqlite3').verbose();
var db = new sqlite3.Database('../db/db_basic.db');
var check;
db.serialize(function() {
db.each("SELECT * FROM server", function(err, row) {
console.log(row.name);
});
});
db.close();
Now, my Question would be, how do I connect to the DB and use those values in the HTML?
Extra:
You need to make a rest API.
The rest API seperates frontend (angular) from backend (database),
it serves you data and it can take care of security.
You can use a framework such as express.js to make a rest API in node.
Express.js can also be used to serve your static files (angular project)
(so you do not need appache or nginx).