Using MySQL with Javascript (node.js) - javascript

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.

Related

How to connect to a Sqlite db from an HTML file via Javascript

I would like to insert data into a SQlite3 db by pressing a button from an HTML file.
In order to achieve this, I wrote a JS script.
Unfortunately, when I press the button, I get this error message in my console.log:
script.js:5 Uncaught ReferenceError: require is not defined
Then, I tried to convert my JS file with browserify but then I got this error:
Cannot read property '_handle' of undefined
Here my HTML and JS codes to reproduce the error:
HTML:
<head>
</head>
<body>
<div>
<label>SQLite3</label>
<button type="button">Connection</button>
</div>
<script src="script.js"></script>
</body>
JS:
function addData() {
const sqlite3 = require('sqlite3').verbose();
let db = new sqlite3.Database('./data.db');
db.run('INSERT INTO info (result) VALUES (10)', function(err, row) {
if(err) {
console.log(err.message);
}
console.log("entry added to table");
});
}
addData();
Browserify works around the problem that browsers don't have native support for the Node.js module system.
Browserify does not work around most other APIs that are provided but Node.js but not browsers. For example, Node.js has the fs module which allows you to access the file system of the computer the code is running on. Browsers, on the other hand, don't allow access except in very particular and limited ways.
Since new sqlite3.Database('./data.db') tries to read data from a file, it will not work in a browser.
Use a different API that is supported by browsers instead (such as IndexedDB or Web Storage.
Alternatively, if you want to share data between browsers, use Node.js to run a web server (e.g. with Express.js) and write a web service through which the database can be accessed.
You can't connect to sqlite databawe from client side you have to connect from server side language. Perhaps you can use NodeJS as server side programming language.
follow those steps then it will work
STEP1
Download and install node js from https://nodejs.org/en/download/
STEP2
Install npm by folloy this instruction
https://www.npmjs.com/get-npm
STEP3
Create Node js project by following this guides http://cassandrawilcox.me/setting-up-a-node-js-project-with-npm/
STEP4
Now you can install sqlite3 via npm.
After that you have to run server. If you are beginner then follow this
https://www.w3schools.com/nodejs/

knexfile.js does not read Dotenv variables

So I am trying out knexjs and the first setup works like a charm. I've set up my connection, created a datastructure and in my terminal i ran $ knex migrate:latest.
It all worked fine... the migrated tables showed up in my database ran the migrate again and got Already up to date.
Now here is where I get an issue: Using Dotenv... Here is my code:
require('dotenv').config();
module.exports = {
development: {
client: process.env.DB_CLIENT,
connection: {
host: process.env.DB_HOST,
user: process.env.DB_ROOT,
password: process.env.DB_PASS,
database: process.env.DB_NAME,
charset: process.env.DB_CHARSET
}
}
};
As far as i can see nothing wrong with it and when i run the script through node no errors show up.
Then I wanted to check if I still could do a migrate and i get the following error:
Error: ER_ACCESS_DENIED_ERROR: Access denied for user ''#'[MY IP]'
(using password: YES)
I am using the same vars only this time from my .env file. But when i look at the error nothing is loaded from it, and yes both the knexfile.js and .env are in the root of my project :) Among the things i tried is setting the path in different ways within require('dotenv').config(); but then it would throw an error from dotenv meaning the file was already correctly loaded.
Can anyone help me figuring this out?
So after some trial and error i finally figured out what was wrong. I don't know what caused it but somehow the install of Knex wasn't done properly...
I un- and reinstalled Knex (local and global). Then first I installed it on the global level and than as a dependency. After that I initialized Knex again ( $ knex init ) and started from the ground up.
I think, but i am still not sure why because i could not find any info about it, the order of installing Knex matters (or mattered in my case and i am not even sure what i did wrong the first time).
On the side
If you are new to Knex and just blindly follow a random tutorial/article and just create a new file for Knex (i.e. knexfile.js), Knex will still work but other packages could fail to execute properly. This is what i don't see in most articles i found, read the documentation on how to generate the files needed (migrations and seeds). Most articles don't cover these steps properly.
Hope this is worth anything

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

Node.js: accessing mysql database

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

How to write test driven programming in node.js?

Recently I got introduced to node.js and packages like express, mongodb and ejs. I have few questions :
As a learning purpose, I have created a github repo of user management which uses express, mongodb and ejs. I have all my functions in routes/users.js file. I need to write test cases all these functions. How to create a test driven programming with this example?
In my routes in app.js file.
app.get('/login', user.login);
app.post('/login', user.loginSubmit);
I need to write different routes to login page renders and submit etc. If there are some ajax request also, then we have lots of routes in app.js file when considering to routes of a single page. Is it like that or need to change my structure?
I recommend you Mocha, it's from the same guy of expressjs.
It supports test coverage for you code, hooks before, after, each and of course it supports async code.
I use it in combination with should.js or even chai.js
A test in mocha looks like, the code is from my own test where I'm using superagent, in order to make requests.
it('requests a permission with valid ticket', function (done){
agent
.post(route.server + '/preq')
.set('Content-Type', 'application/json')
.set('Authorization', 'Bearer ' + ACCESSTOKEN)
.send({ticket: TICKET})
.end(function (req,res) {
res.should.have.property('statusCode').that.equals(201);
var location = .....
res.headers.should.have.property('location').that.is.equal(location);
done();
});
})

Categories