Connect MySQL database with node JavaScript application - mysql

I make a node JavaScript app and deploy it on cPanel using SSH.
App is working fine without database but when I connect the app with database on cPanel (GoDaddy) it takes times and shows the message "Error establishing a database connection".
My connection code
const mysql = require('mysql');
const express = require('express');
const app = express();
var pool = mysql.createConnection({
host: 'localhost',
user: '<MY_USER_NAME>',
password: '<MY_PASSWORD>',
database: '<DB_NAME>'
});
pool.connect(function(err) {
if (err) throw err;
else{
console.log("Connected!");
}
});
module.exports = pool;
route where DB interact,but lost the connection.
app.post('/loginn', (req, res) => {
var id = req.body.id
console.log("user_id= "+id);
var sql = "select * from users where id NOT IN ('" + id + "') ";
pool.query(sql, function (err, rows) {
if (err) throw err;
else {
res.render('allusers', {
users: rows,
user_id:id
})
}
});
});

This answer is going to take the form of a debugging journey, because that's the only way I can see to get to the bottom of your issue.
Let's do a dead-simple representation of your app to make sure that you can send a query to MySQL and receive a response from a route-handler in Express. Setup your app like this:
const mysql = require('mysql');
const express = require('express');
const app = express();
const PORT = // define the PORT for your host
var connection = mysql.createConnection({
host: 'localhost',
user: '<MY_USER_NAME>',
password: '<MY_PASSWORD>',
database: '<DB_NAME>'
});
connection.connect(function(err) {
if (err) console.error(err);
console.log("Connected!");
});
app.get('/db-test', (req, res, next) => {
var id = // fill in a user_id that you know exists
var sql = `SELECT * FROM users WHERE id NOT IN ('${id}') `;
console.log(sql); // confirm you are sending the sql request you believe you should be sending
connection.query(sql, function (err, results, fields) {
if (err) console.error(err);
console.log(`results: ${results}\nfields: ${fields}`);
});
});
app.listen(PORT);
And then hit the route /db-test from your app, and see what happens. If this works, then we will have at least proved that you CAN make requests between Express and MySQL. Right now, I'm not sure you can, so I'm not sure what to debug.

Related

Cannot enqueue Handshake after already enqueuing a Handshake

const app = require('./app');
var mysql = require('mysql');
const server = app.listen(3000, () => {
console.log(`Express is running on port ${server.address().port}`);
});
I learning nodejs 3 day but i don't know how can i fix it i try to fix it but not work.
Someone Help me please
I don't know what i wrong. I want to insert data into mysql with pug
be like login with html and use php to select data in phpmyadmin
register in pug and data send to nodejs and node post data to mysql
I'm sorry my English and gramma so bad :(
const express = require('express');
var mysql = require('mysql');
const router = express.Router();
const app = require('../app.js');
var conn = mysql.createConnection({
host: "localhost",
user: "root",
password: "1234",
database:"project_test"
});
conn.connect(function(err) {
if (err) throw err;
console.log("Index Connection!");
});
conn.connect(function(err) {
if (err) throw err;
console.log("Connected!");
var sql = "INSERT INTO customer (name, address) VALUES ('Company Inc', 'Highway 37')";
conn.query(sql, function (err, result) {
if (err) throw err;
console.log("1 record inserted");
});
});
module.exports = router;

Why does my middle end node server stop running after I connect to a dabatase

Question: Why is my middle end server not responding after connecting to a database?
Hello, so I have a simple mysql database server running and open in mysql workbench (I ran a test and it is working), and I also have a simple middle end node app to handle and process requests. I can even run a query to make a database in mysql before the api stops responding.
The problem: after I connect to my database, my middle end end points stop working. such as my default page "/" for "hello world". I have very simple and basic node db connection code so I'm not sure why it's failing.
var express = require('express')
var app = express()
var https = require('https')
var mysql = require('mysql')
var cors = require('cors')
app.use(express.json())
var myLogger = function (req, res, next) {
console.log('LOGGED')
next()
}
const db = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'password',
port: '3306',
database:'mydbtest666'
});
db.connect(function (err) {
if (err) throw err;
console.log("Connected!");
db.destroy();
});
app.get('/', function (req, res) {
res.send('Hello World!')
})
app.listen(5000)
I am using the logger to help log commands, and it will show that the endpoint was called, but no data is being shown on my screen and again the page just loads and loads.
I thought closing/destroying the connection would work, but it is not. Would a try catch change anything??
Here's another attempt with my signup but the middle end still freezes and with this attempt it no longer connects to the database:
app.post("/users/signup", (req, res) => {
const username = req.body.username
const password = req.body.password
db.connect(function (err) {
if (err) throw err;
console.log("Connected!");
try {
db.query("INSERT INTO users (username, password) VALUES (?,?)", [username, password], (err, result) => { });
db.destroy();
} catch (err) {
console.log(err);
}
});
});

Connection_refused when trying to use MySQL and node.js. When using cmd it does work

I created a server.js file which looks like this.
var express = require('express'),
app = express(),
port = process.env.PORT || 3000;
app.listen(port);
console.log('todo list RESTful API server started on: ' + port)
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "**",
password: "**",
database: "test"
});
app.get('/nodeapi/getimg',function(req,res){
con.connect(function(err) {
if (err) throw err;
con.query("SELECT * FROM images", function (err, result, fields) {
if (err) throw err;
console.log(result[1].image);;
});
})})
When I run this file in my command terminal I get the correct result.
When I create a http.get function like this for my ionic app:
getimg(){
var url = 'http://localhost:3000/nodeapi/getimg';
this.http.get(url).subscribe(responseData => console.log(responseData));}
I get an error saying net::ERR_CONNECTION_REFUSED. I have looked everywhere but cannot seem to find it. I am using phpmyadmin for the database. Would anyone please be so kind to explain to me what I am doing wrong.
Give this example a try. Also, do you expect more than one result from your query? If not you will want to use result[0] not 1 to get the first (and maybe only) result (located at index 0).
var express = require('express');
var cors = require('cors');
var mysql = require('mysql');
var port = process.env.PORT || 3000;
var app = express();
app.use(cors());
app.options('*', cors());
var con = mysql.createConnection({
host: "localhost",
user: "**",
password: "**",
database: "test"
});
app.get('/nodeapi/getimg', function(req, res) {
con.connect(function(err) {
if(err) throw err;
con.query("SELECT * FROM images", function(err, result, fields) {
if(err) throw err;
console.log(result[1].image);
res.send(result[1].image); // send the value back to the caller.
});
})
})
app.listen(port, function() {
console.log('CORS-enabled web server listening on port 80')
})

How to make an express route that makes a mysql delete query for a specific ID

I'm trying to make a post request in express that when fired, deletes a row in my Tasks MySQL table, which is connected to a specific user ID. I'm not sure how to go about it... I think I have to use req.params.id in my code somewhere, but I don't know if thats all I need or if thats even right to begin with.
Here is what I have so far:
const express = require("express");
const app = express();
const mysql = require("mysql");
const bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({extended: true}));
const connection = mysql.createConnection({
host: "localhost",
user: "root",
password: "PASSWORD",
database: "DATABASE"
});
connection.connect(function(err) {
if (err) {
console.log("Your connection to the database failed \n");
} else {
console.log("Your connection to the database was successful \n")
}
});
app.post("/deleteTask", function(req, res) {
let remove = "DELETE FROM Tasks WHERE "; // finish the query
connection.query(remove, function(err, result) {
if (err) {
console.log("The delete query failed");
res.sendStatus(500);
throw err;
} else {
res.sendStatus(200);
console.log(result);
}
connection.end();
});
});
Yes, first I suggest you to read the doc about routing : https://expressjs.com/en/guide/routing.html
After If it was my jobs I'll get the taskId with something like
app.post("/deleteTask/:taskId", function(req, res) {
const taskId = req.params.taskId;
let remove = "DELETE FROM Tasks WHERE "; // finish the query
...
});

Angular 4 - display date from database

I need display data in table from MySql database, but I dont know how it do this.
I tried found something example or example application with source code, but I nothing found.
Maybe someone help me with this?
I tried with node.js express:
var mysql = require('mysql');
var https = require('https');
var con = mysql.createConnection({
host: "https://adress to database",
user: "user",
password: "password",
database: "db"
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
});
But i get error:
Error: getaddrinfo ENOTFOUND
here is a simple way to get data from mySQL and export it as json:
var http = require('http');
var mysql = require('mysql');
var bodyParser = require("body-parser");
var express = require('express');
var app = express();
var pool = mysql.createPool({
host: 'db location',
user: 'username od db',
password: 'something',
database: 'yourdatabase',
port:3306
});
// define rute
var apiRoutes = express.Router();
var port = 9000;
apiRoutes.get('/', function (req, res) {
res.json({ message: 'API works' });
});
apiRoutes.get('/data', function (req, res, next) {
pool.getConnection(function (err, connection) {
if (err) {
console.error("error hapened: " + err);
}
var query = "SELECT * FROM imena ORDER BY id ASC";
var table = ["imena"];
query = mysql.format(query, table);
connection.query(query, function (err, rows) {
connection.release();
if (err) {
return next(err);
} else {
res.json({
success: true,
list_users: rows
});
}
});
});
});
app.use('/api', apiRoutes);
// starting
app.listen(port);
console.log('API radi # port:' + ' ' + port);
But i still suggest that you start using noSQL databases like firebase because of they are simple and faster.
In order to show data from MySQL Database, you need to provide application interface(s) to Angular environment and only then Angular can use the data. There are few techniques in which you can design interfaces, REST is the most popular though.
First you need to understand that Angular is Front-End framework and it can only send requests to backend such as Node js, PHP etc.Thus, first you need to chose your backend. Node is popular with express js module, but if you still don't have mySQL set, go for firebase real time database. If you decide node js => express => mySQL check tutorial online.