If you wanted to push something live with Node JS, Mongo DB & Express does this suffice as a secure way to connect to the Mongo DB?
Can someone explain this code from a security perspective?
===
Alot of tutorials simply use...
var mongoClient = new MongoClient(new Server('localhost', 27017));
Mongos Documenation includes...
var MongoClient = require('mongodb').MongoClient;
// Connect to the db
MongoClient.connect("mongodb://localhost:27017/exampleDb", function(err, db) {
if(!err) {
console.log("We are connected");
}
});
===
Code is based on Mongo Documentation - http://mongodb.github.io/node-mongodb-native/api-articles/nodekoarticle1.html#getting-that-connection-to-the-database
You're not missing much. The best thing to do with most database servers is to secure them by keeping them away from the public network.
The same is true of e.g. MySQL--it lacks enterprise authentication methods like Kerberos (requested since 2004: http://bugs.mysql.com/bug.php?id=6733).
You just need to keep your DB server inside the trusted LAN. If you want to use a login with password, it's better than nothing, but exposing most databases to the outside world is a bad idea, because they lack simple protections like bad-password rate limiting. They're just not meant to be user-facing in that way.
Related
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 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.
I am trying to develop the simple web application by using HTML, NodeJS, and Postgres. is it possible to develop the web application without using ExpressJS.
Please let me know how to do the basic CURD operations by using NodeJs, Javascript, and Postgres without using the ExpressJS framework.
Thanks in advance.
Yes, you can skip express But It ain't gonna be easy.
But there is something else :
is it possible to develop the web application without using ExpressJS
It can mean,
you either use other frameworks, or
Node.js web app from scratch
In the first case, you have options to choose from. There are MVC frameworks like hapi, Flicker.js etc, REST API frameworks like restify, loopback etc
In the second case, you are faced with the job of writing custom implementations of many features provided by express.
I'm continuing Assuming you meant the second case...
For creating the HTTP server, you can use node's HTTP Module
var http = require('http');
http.createServer(function (req, res) {
res.write('Hello World!');
res.end();
}).listen(8080);
This method makes it a pain to write a REST API
req.url; //the request URL
if(url == '/users/create')
{
//do this
}
else if(url == '/users/details')
{
//do that
}
To connect to postgres, you have to use node-postgres (pg) anyways (pg documentation)
const { Client } = require('pg')
const client = new Client()
await client.connect()
const res = await client.query('SELECT $1::text as message', ['Hello world!'])
console.log(res.rows[0].message) // Hello world!
await client.end()
As for the CRUD operations, apart from their API implementation, the code is going to be almost the same. So you can refer to the tutorials that use express.
https://mherman.org/blog/postgresql-and-nodejs/
It is not necessary to use Express. Express is just a library that uses Node-Functions to make it easier for you to implement a Webserver.
There are plenty alternatives out there: A small overview of the 'best'
For the CURD Operations see the documentation of the Frameworks.
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.
am very new to both mongodb and java script.
Now i need to connect to my local mongodb instance using java script in order to get the list of documents.
any help?,
thanks in advance.
You can use mongoose to connect to a mongoDB database : http://mongoosejs.com/
Take a look at here,
https://mongodb.github.io/node-mongodb-native/driver-articles/mongoclient.html
var MongoClient = require('mongodb').MongoClient
, Server = require('mongodb').Server;
var mongoClient = new MongoClient(new Server('localhost', 27017));
mongoClient.open(function(err, mongoClient) {
var db1 = mongoClient.db("mydb");
mongoClient.close();
});
In order to connect to database, you need to connect your application to a server( not sure if the application could connect to database directly but from what I learnt, it seems server side language is needed). Thus, if you want to connect to database with javascript only, you may consider using node.js+express to connect to mongoDb. I think this link is quite useful. I also learnt from this website. This website teaches you how to do that from scratch and instructions can be easily followed. If you prefer to use php for server side, I just googled this website which might help. It seems to me that php is easier to learn but if you only need basic CRUD operation, the website mentioned is enough.