Node.js: accessing mysql database - javascript

I am writing a Node.js application. In my node-modules/abc/static/example.js file, I want to access the mysql records by querying to the database. Is it possible to do so?
When I include mysql like this:
var mysql = require('mysql');
I get an error:
Uncaught ReferenceError: require is not defined
Is it because it is on client side? What are the other options to access mysql database from the 'example.js' file?

I'm going to guess that you're attempting to use server side js in the client side.
You need to npm install a mysql adapter, #coreyg suggested this one (https://www.npmjs.com/package/mysql).
Set up a nodejs project (if you have not already done so):
npm init
npm install --save mysql
You would then typically create some sort of webapp that would serve up a url in the client side. You'd then (using ajax) request the url.
Behind the scenes your webapp then would query the mysql database (using the adaptor you installed) with whatever query you had in mind.
Once your ajax call had finished you'd run your callback which would do what you wanted with the data that had been returned from the database.
Thats the basic theory. If you want further information on how to do this I'd suggest reading this question: How do I get started with Node.js

Following on Neil Munro's Answer,
after initiating nodejs and installing mysql npm package,
you can actually execute your code from the terminal. to do that,
you can create a new js file on the same folder you are executing those commands,
say mysqlTestProject.js
inside this file, you can put what you had previously, (require stuff and all). for example:
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'me',
password : 'secret',
database : 'my_db'
});
connection.connect();
connection.query('SELECT 1 + 1 AS solution', function(err, rows, fields) {
if (err) throw err;
console.log('The solution is: ', rows[0].solution);
});
connection.end();
`` codes were taken from https://www.npmjs.com/package/mysql
and then from the terminal (still on the same folder as you were),
type in this line
node ./mysqlTestProject.js

Related

Using MySQL with Javascript (node.js)

I've just started learning Node.js. I come from a PHP background, so I started with MySQL.
So, I wanted to try executing some basic MySQL queries using javaScript.I write the queries, this way:
filename: test.js
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "test",
});
con.connect(err => {
if (err) throw err;
console.log("Connected!");
const q = "INSERT INTO testing VALUES(3, 'MILLENNIAL', 19, 'STUDENT', 'CSE')";
con.query(q, (err, result) => {
if (err) throw err;
console.log("done");
});
});
When I run the only the javascript file this way: node test.js the query gets executed but when I connect the same file to a html file, this way:
<script src="test.js"></script>
the query doesn't get executed... It gives an error in console: Uncaught ReferenceError: require is not defined
I have feeling that I am not using something very important here. Am I missing something?? Please help me go further.
I am so sorry if this is very silly but, please help me with this. Thank you in advance.
node.js is javascript runtime which uses javascript syntax, which is meant for server-side language. What you trying is to use nodejs script in frontend. require is not defined - because its applicable only for node, to use other modules in plain javascript you will need to use cdn or packages like browserify, webpack. Checkout docs if you are interested.
I will try to explain from a PHP perspective.
When you write PHP, usually your resulting file is an HTML and you embed your PHP code in it, so it renders out without PHP to the requesting browser.
In node, this is different. We don't write the HTML with node code embedded. Node focuses more on backend and frontend separation. You write your backend to reply to your front end.
The backend is where you type var mysql = require('mysql');
You can use something like express vs koa to serve the resulting query to the front end.
Here's a good tutorial to start https://geshan.com.np/blog/2020/11/nodejs-mysql-tutorial/
I usually recommend Koa because it's up updated more regularly now, but express is basically the same thing!
Hope this directs you in the right direction.

Database connection works in node.js file but not in script tags

I'm trying to connect to my MongoDB database (or to the server actually MongoLab), it works fine when I have the code in name.js file but it doesn't work when I have it in HTML file inside <script> tags.
Also, I only have those 2 files in my folder, and I'm using Cloud9 framework.
This is my JavaScript code:
// JavaScript File
var MongoClient = require('mongodb').MongoClient;
var url = "x";
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("mkndb");
var myobj = { name: "Company Inc", address: "Highway 37" };
dbo.collection("test").insertOne(myobj, function(err, res) {
if (err) throw err;
console.log("1 document inserted");
db.close();
});
});
Thank you
The package mongodb you are requiring is a node.js package, it runs only on the server side and not in the browser.
To access a MongoDB on the client side, you can use the REST webservice.
It allows rudimentary queries through XmlHttpRequests.
To enable it, you have to start mongod with the --rest parameter.
Then you can then query it like this:
http://127.0.0.1:28017/someDatabase/someCollection/?filter_name=someFilter
You seem to be using the Mongodb node client. Inserting the script in html page with tags would not work in the same way as you expect. You have few ways to achieve what you are looking for :
1. You can build a nodejs server component which can handle the requests from browser application. The nodejs server then interacts with mongodb and respond. This again can be achieved in few ways.
a. Deploy nodejs in Lambda. Mode details here - https://docs.aws.amazon.com/cloud9/latest/user-guide/lambda-functions.html . You can then connect from the browser as given here - https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/browser-invoke-lambda-function-example.html
b. Deploy in EC2
2. If you do not want to build/deploy the node.js server, try using the mLab Data API. (http://docs.mlab.com/data-api/) . This works only for this special case where you are trying to connect to MongoLab

To connect create-react-app reactJs with mysql

I have problem in connecting my create-react-app with mysql using npm.
Its working in nodejs when i tried seperately without npm. But, When i trying to connect using npm install mysql, It throws me an error...
TypeError: http.IncomingMessage is undefined
./node_modules/express/lib/request.js
Here is my code:
var express = require('express');
var mysql = require('mysql');
var connection =mysql.createConnection({
host: 'localhost',
user: 'user',
password: '',
database: 'reactproject'
});
connection.connect(function(err){
if(!err) {
console.log("Database is connected ... nn");
} else {
console.log("Error connecting database ... nn");
}
});
This will not work from react-app, since react code will run from client side.
You should use my-sql connection in different app and run in different port and call as api connection.
Thanks.
Adding from an #ashik answer is correct, but if you still want to use MySQL and reactjs simultaneously, you can start by creating your own boilerplate, there you can use MySQL on the server side and create APi/web service without having to separate the APi server and client projects reactjs.

Modifying HTML Website from Node.js Server to Display File Data

So. I'm a total noob. And most of my question is geared towards just not understanding data transfer or Web servers properly.
Anyway, I am creating a project which hosts a very simple and lightweight Node.js server. In this server, I need to create a website to be able to view file data which resides on the server. On the server, I have a directory listing that goes something like this...
- info
--- client_IPAddress1
------ dataFile1.info
------ dataFile2.info
------ dataFile3.info
--client_IPAddress2
------ dataFile1.info
------ dataFile2.info
------ dataFile3.info
--client_IPAddress3
------ dataFile1.info
------ dataFile2.info
------ dataFile3.info
On the node server, I need to be able to read this file data, and modifying a table element on an html page to display the contents of the files. So far, all I know how to do is display the html page directly like this...
if(request.method == 'GET' && request.url == '/'){
response.writeHead(200, {"Context-Type": "text/html"});
fs.createReadStream("clientMonitor.html").pipe(response);
Now, I have a button like so...
<div class="refresh-btn" href="http://169.254.0.4:8888/client-data">
<p><b>Refresh</b></p>
</div>
Which I want to be able to refresh that data to display to a table element. So, on the node.js server what do I do here?
}else if(request.method == 'GET' && request.url == "/client-data"){
//TODO
}
I am a complete and total stranger to node.js. A quick solution or a link to a helpful website, or simple a link to a tutorial about data handling that covers topics akin to these would be extremely helpful. I am running this on a Raspberry Pi using Rasbian Jessie. If anyone knows another solution that they could point me for this platform, again, it would help.
Not sure what the output needs to be following your example, but I would surly start by using express.js in your project. This will simplify greatly your RESTfull api.
Depending on how noob, you are to node, I will try to guide you thru the simplest way I can! ;)
You first need to install Express in your node project.
From the command shell you type npm install express --save to install the node_module. The --save adds the dependency to your package.json. (Depending on your user's role, you might have to use the sudo command (sudo npm install express --save)
Using the following link Express "Hello World" example you will find the simplest example on how to use Express.
So if we use your example your setting might look like this.
var express = require('express')
var app = express()
app.get('/', function(req, res){
res.sendFile(__dirname + '/clientMonitor.html');
});
app.get('/client-data', function(req, res){
/* Depending on what you use on your client side,
you may get data here than send a response in json or flat data.*/
res.json(aJsonObject); // For json response {"Context-Type": "application/json"}
// OR
res.send('AnyValue'); // Will send 200, {"Context-Type": "text/html"}
// OR
res.sendFile(__dirname + '/someFile.html');
});
app.listen(8080, function () {
console.log('Example app listening on port 8080!')
})
For your client side, you may use any plugin such as DataTables.net or custom-made function that updates your data in your table using Ajax calls to refresh the information.
Hope this will help solve your issue!
If you decide to use POST instead of get, you will do something like :
app.post('/client-data', function(req, res){
var data = req.body.data;
}
Or if you wish to use queryStrings in the Get url parameters, you will do soemthing like :
app.get('/client-data/:id', function(req, res){
var data = req.params.id;
}

How do I allow the node pg module communicate with my Windows postgresql server?

I have a node server on localhost. In it is the pg module:
//above is express requires
var pg = require('pg');
var client = new pg.Client();
client.connect((err)=>{
if(err) throw err;
client.end((err)=>{
if(err) throw err;
});
})
//below is basic express server stuff
I have, I believe, a postgresql server running on windows. I have pgadmin open, there is a localhost:5432 section, and inside is a "test" database I have created.
My node server currently throws:
error: password authentication fails for user 'myname'
I do not understand how I can, either in postgresql's Windows client, set default username/password that is then added to environment variables, or, in Windows add the proper environment variable key/value pairs that the node pg module expects so it can login, or, tell the node pg module how to login to postgresql, or, whether I am even going down the right path at all.
How can I allow my node pg module to connect to my localhost postgresql server?
EDIT: I tried to follow the instructions in this SO answer, however I would always recieve "access denied" errors no matter where I pointed the db creation to, whether I used cmd or powershell in admin or no, and no matter the permissions I set for files. I'm now primarily interacting with postgresql through the pgadmin III GUI.
EDIT2: I tried modifying the pg initialization by doing:
var connectstring = 'postgres://me:password#localhost/dbname';
var client = new pg.Client(connectstring);
I received the same error, using the same exact login details I was prompted with by pgadmin III.
EDIT3: According to these docs, I should possibly have that list of environment variables? If not, where can I find this information so I can manually set these environment variables? Is this the right path to go down?
Use:
var pg = require('pg');
var config = {
user: 'foo',
database: 'my_db',
password: 'secret',
port: 5432
};
var pool = new pg.Pool(config);

Categories