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.
Related
I have a NodeJS application which uses oracledb library to connect to an Oracle Database . It's using the following code to try to connect to the database:
this.oracledb.fetchAsBuffer = [this.oracledb.BLOB];
const dbconfig = {
user: 'mysuser',
password: 'mypass',
connectString: '10.xxx.xx.xxx/MYORCLID'
};
console.log("Trying to get connection");
return await this.oracledb.getConnection(dbconfig);
But, I'm receiving the following error now during the "getConnection" method:
"Error: ORA-03135: connection lost contact"
Please, is there anything wrong with this code? It was working before but suddenly I started to receive the above message. From where should I start to check?
I've tried telnet and it worked too, so I'm not sure if this is a firewall issue.
I managed to solve the issue.
It was an internal blocking issue inside our network. They use a type of application which checks the origin hostname, linux user, application name and other properties before allowing access to the database.
After talking to my Infra and DB Team, they checked and liberated the access, and then everything worked as it should.
Thanks!
I have created a little web app on my own server. It contains only a few html, css and javascript files. I want to put a node.js with a simple code:
var mysql = require('mysql');
var fs = require('fs');
var con = mysql.createConnection({
host: "example",
user: "example",
password: "example",
database: "example"
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
con.query("SELECT *example", function(error, data, fields) {
if (error) throw error;
const jsonData = JSON.parse(JSON.stringify(data));
console.log("jsonData", jsonData);
});
});
The question is how to execute node.js on a server? I want to do it with a javascript so lets suppose I want to write an execution between <script> tags. Is it possible?
I want to do it with a javascript so lets suppose I want to write an execution between <script> tags. How to do it?
You don't, per se.
Putting JS code in a script element in an HTML document and then giving it to a browser to run is one way to execute JS.
Putting JS in a file and running it with Node.js is a different way to run JS (and one which gives access to a different set of APIs, which is why JS running in Node.js can directly access a database but JS in a browser can't).
To trigger the execution of JS with Node.js from a browser you would typically:
Wrap the JS function you want to execute in Node.js in a web service (typically using the Express.js module)
Use Node.js to run that web service application (typically using PM2 to monitor it and restart it if it falls over)
Have a seperate JS program run in the browser and use Ajax to make an HTTP request to that web server.
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 would love to know a few things about Node.js async and MongoDB.
If the server starts before my connection to, and my templates or Ajax depend on data from the database will serving (I precompile my handlebars) the HTML file fail or will my templates/Ajax wait for the connection and then continue?
If it works, I would love to understand better how exactly it worked!
If it fails, how can I "fix" it elegantly?
This is an example of a solution, using hoisting (seems bad to me tbh):
//connect to db
mongodb.connect("someDBplace",
(err, db)=>{
if(err){
return generalLogger.error(`The database has failed to connect: ${err}.`);
}else{ //start the server now:
generalLogger.info(`Connected to database: ${stringify(db.databaseName)}.`);
server.listen(`${port}`, (err)=>{
if(err){
generalLogger.error(err);
}
//for demo: console th eMIMEtype
generalLogger.info(`The Server started on port: ${port}.`);
});
}
});
Yes, this is a correct way to do it. If you want to make sure that the database is available before the server starts serving requests, then you need to start the server in the callback of the database connection method.
Some higher level frameworks like Hapi may provide you some mechanisms to simplify the case when you need to wait for several things before starting. For example see the Hapi plugins:
https://hapijs.com/tutorials/plugins
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.