Nodejs/Express Ajax call to MySQL - mysql

I am looking for a sample and how to make ajax call to get data from MySQL for Nodejs/Express projects.
I have database connection established in app.js file. That's starts when node is running. This is db.js file.
const mysql = require('mysql');
let db_connected =false;
const ut_mysql_con = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'pass',
database: "db"
});
mysql_con.connect(function(err) {
if (err) throw err;
else {
console.log("Connected!");
db_connected = true;
}
});
module.exports = mysql_con;
module.exports.db_connected = db_connected;
I also have an ejs file for front end from which ajax call is made.
<script>
$(document).ready(()=>{
//this where actual call would go if i knew how to do it.
});
</script>
I am comfortable with writing actually queries, but can't find a way of properly using ajax.
Thanks in advance for any guidance.

Related

Unable to connect React Native app to MySQL database using Node.js. (Error: connect ECONNREFUSED 127.0.0.1:3306)

I am very new to programming so I do apologize if this is a really simple question.
So, I have been trying to connect my React Native application to the MySQL Database using Node and Express server, but I keep on getting the following error (I have checked other stackoverflow questions as well, but nothing has helped):
Error
I have checked my host name and port number multiple times and the all the information seems to be correct. I am not sure what is wrong with the following code:
var express = require("express");
var app = express();
var mysql = require("mysql");
var bodyParser = require("body-parser");
const { application } = require("express");
app.use(bodyParser.json({ type: "application/json" }));
app.use(bodyParser.urlencoded({ extended: true }));
var connection = mysql.createConnection({
host: '127.0.0.1', // Your connection adress (localhost).
port: "3306",
user: "root", // Your database's username.
password: "", // Your database's password.
database: "birthdays", // Your database's name.
});
connection.connect(function (error) {
if (error) console.log(error);
else console.log("connected");
});
// Starting our server.
app.listen(4547, () => {
console.log("Go to http://localhost:4547/dinners so you can see the data.");
});
app.get("/users", function (req, res) {
con.query("select * from users", function (error, rows, fields) {
if (error) console.log(error);
else {
console.log(rows);
res.send(rows);
}
});
});
I run this code by typing "node fileName.js" in the terminal.
I don't know if this is helpful, but I have also connected by MySQL database to MySQL Workbench.
Any help is appreciated!

How to fetch data from MySQL database with Node

I'm new to react, developing a recipe-app and I got a problem while displaying the data from MySQL database. The connection was created successfully, however, I'm not sure about how to reach the data. When I run node server.js in my terminal, I get "connected", When I visit the localhost:8080/users, I get "This site can't be reached" message and in my terminal:
`events.js:187
throw er; // Unhandled 'error' event
^
Error: Cannot enqueue Handshake after already enqueuing a Handshake.`
I'm a little stuck here. Anyone knows a solution or direct me a little bit? Thank you so much!
Server.js
const express = require('express');
const app = express();
const PORT = 8080;
const mysql = require('mysql');
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'root',
database: 'recipe_app'
});
connection.connect((err) => {
if (err) throw err;
console.log('Connected!');
});
//creating route for the app
app.get('/users', (req, res) => {
connection.connect();
connection.query('SELECT * from users', function(err, rows, fields) {
if (!err) {
res.send(JSON.stringify(rows));
} else {
console.log('Error while performing Query.');
}
});
connection.end();
});
//making server listen to request
app.listen(PORT, () => {
console.log(`Server running at : http://localhost:${PORT}/`);
});
You're trying to reconnect to mysql after the connection has been established.
See my comments on the code below
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'root',
database: 'recipe_app'
});
connection.connect((err) => { // This creates the connection
if (err) throw err;
console.log('Connected!');
});
And when you're trying to resolve your GET routes, you're trying to connect again
//creating route for the app
app.get('/users', (req, res) => {
connection.connect(); // reconnect here
Since you're using the default connection method, trying to connect to an already established connection will cause the driver to throw a Handshake error.
If you want to re-use the connection, store it in a variable and then re-use it in other part of your code.
If you want to manage multiple connections instead, I suggest you to look at createPool instead.
Try removing the connection.connect() and connection.end() from app.get

mvc with node/express and mysql

I'm getting confused. All the tutorials I see with mySql end up with something like this:
in models/dbconnection.js
var mysql = require('mysql');
port = process.env.PORT || 3333;
if (port == 3333) {
var connection = mysql.createConnection({
host: 'localhost',
port: 3306,
user: 'root',
password: 'root',
database: 'nameDataBase',
insecureAuth: true
});
} else {
console.log("Error");
}
connection.connect();
module.exports = connection;
And then in routes/user.js
...
router.delete("/:id", verifyToken, (req, res) => {
const newLocal = "DELETE FROM login_user WHERE id = ?";
connection.query(newLocal, [req.params.id], (err,rows,fields) => {
if (err) {
res.sendStatus(500);
return;
}
console.log(rows.affectedRows);
res.status(200).send({delete: rows});
});
});
module.exports = router;
model and controller aren't getting mixed here? If tomorrow I want to change the type of database, I have to make changes in the model and in the routes. Shouldn't I make functions such as getAllUsersBlaBla(params) in something like models/user.js and then call it from routes/user.js ?
I agree. There shouldn't be any database queries in the router, which is considered part of the controller in MVC.
The model should provide wrapper functions around database queries that can be called from the controller.
A lot of node apps (and probably tutorials) will choose simplicity rather than modularity, that's why you would see code like that.

node js express server using mysql hangs up, how to restart automatically?

I want to have a server running to make some entries in a database. I havent done that before. Im using node.js, express for the server and mysql with node-mysql and host it on uberspace as a low-cost webhosting service. When im starting the server with 'nohup node app.js &' everything seems to work fine, but after some time, I dont get any response from the server in a webbrowser anymore. I think the server just hang up and I want to restart it automatically. Here the simple code for my app.js:
var express = require('express');
var app = express();
var mysql = require('mysql');
var connection = mysql.createConnection({
host : '***',
database: '***',
user : '***',
password: '***',
port: 3306
});
connection.connect(function(err) {
console.log(err);
});
app.get('/test', function(req,res) {
var post = {ID: 1, User: "testuser"};
var query = connection.query('INSERT INTO testtabelle123 SET ?', post, function(err, results){
console.log(err);
});
console.log(query.sql);
res.send(query.sql);
});
I guess I simply just have to make a little change for automatically restart in the code and maybe use some sort of middleware/tool for that. Can you tell me what to do? Havent found simple solutions on SO so far.
Problem occurs because mysql is closing connection when there is no connection (after sometime). Add this to make connection alive forever:
setInterval(function () {
connection.query('SELECT 1', [], function () {})
}, 5000)
Relevant issue: https://github.com/felixge/node-mysql/issues/1337

Node.js gives error "Can't find variable require"

I'm trying to connect to my local mysql database by using node.js on my website. I have installed node.js on my laptop. This is my code that is executed:
function registerUser()
{
var mysql = require("mysql");
var connection = mysql.createConnection( {
host: 'localhost',
user: 'root',
password: '',
database: 'Fountaint_News_Database',
port: 3306
});
connection.connect();
var query = connection.query('INSERT INTO registered_users VALUES ("test", 22)',
function(err, result, fields) {
if (err) throw err;
console.log('result: ', result);
});
connection.end();
console.log('Connection closed');
}
I haven't done anything else, I'm not sure if there is anything else to setup, but when I runt I just get this error "ReferenceError: Can't find variable: require".
I hope that someone can help me.
Are you running this code on the server side, not on the client don't you? I mean saving this file on a .js file, running via console via
node yourfile.js
after obviously a
npm install mysql
in the same directory?
Obviously you need to bind the registerUser() function to some event :)