// So I am using mysql with node and express framework and the first time I created a test example everything worked fine. But then I tried to create a second project and now the routing seems to not being read.
And the respond back I get is:
[nodemon] restarting due to changes...
[nodemon] starting `node app.js`
Server started on port 8000
mysql connected...
//I am also supposed to get the result back:
OkPackege{...
...
...
...
}
//But I am not getting it. Any Ideas...? thanks.
The scrips that i have are as follow:
const express = require('express');
const mysql = require('mysql');
const db = mysql.createConnection({
host : 'localhost',
user : 'root',
password : 'LEoking1987'
//database : 'nodesql'
});
db.connect((err) => {
if(err){
throw err;
}
console.log('mysql connected...');
});
const app = express();
// Creates satabase if it does not exist yet.
app.get('/createdb',(req,res) => {
let sql = 'CREATE DATABASE nodesql';
db.query(sql, (err, result) => {
if(err) throw err;
console.log(result);
res.send('Database created...');
});
});
app.listen('8000',()=>{
console.log('Server started on port 8000');
});
add debug: true in your mysql connection params like
mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'LEoking1987'
database: 'nodesql'
debug: true,
})
Related
I make a connection to mysql using node js,
connection is successful, event if i put a wrong port,
but query didn't return any results.
mysql version for node js is : "mysql": "^2.18.1"
data base version : 5.5.47
(port : number or string : same result)
var express = require('express');
var mysql = require('mysql');
var app = express();
//
var connection = mysql.createConnection({
host: 'localhost',
database: 'mydb',
user : 'root',
password: 'pwd',
port : '3306'
});
connection.connect(function(error){
if(!error){
console.log(error)
} else{
console.log('Connected')
}
});
connection.query("SELECT * FROM members", function(error, rows){
if(!error){
console.log("Error in the query")
console.log(error)
}else{
console.log("successfull")
console.log(rows)
}
})
app.listen(4000)
Following logic is incorrect. it says if not error then log error so you will never get your rows.
if(!error){
console.log("Error in the query")
console.log(error)
}else{
console.log("successfull")
console.log(rows)
}
Remove the !
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
I am trying to create a simple nodejs code using express and mysql.
const express = require('express');
const mysql = require('mysql');
const db = mysql.createConnection({
host : 'localhost',
user : 'admin',
password : ''
});
db.connect((err) => {
if(err){
console.log('Error while connecting');
}
console.log('Connected');
});
const app = express();
app.get('/createdb',(req, res) => {
let sql = 'CREATE DATABASE nodemysql';
db.query(sql,(err,result) => {
if(err){
console.log("error while creating database");
}
console.log('result: '+result);
res.send('database created..');
});
});
app .listen('4200',() => {
console.log('Server started on port 4200');
});
The response is sent to the browser that says
database created..
but the result it throws is undefined. Also the console that says
Error while creating database is printed
Error I am getting is
[nodemon] restarting due to changes...
[nodemon] restarting due to
changes... [nodemon] starting node index.js
Server started on port 4200
Connected error while creating database
result: undefined
I am not sure on what I am missing out. Please help.
Below code should work fine, try to execute the below code in a .js file. If it works, then we would be sure that nothing wrong in the conf part.
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "root"
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
con.query("CREATE DATABASE mydb", function (err, result) {
if (err) throw err;
console.log("Database created");
});
});
I am not an expert, but added the keyword 'function', like below:
app.get('/createdb',(req, res) => {
let sql = 'CREATE DATABASE nodemysql11';
db.query(sql, function(err,result) => {
if(err){
console.log("error while creating database");
}
console.log('result: '+result);
res.send('database created..');
});
});
Try this, it will work
app.get('/createdb',(req, res) => {
db.query('CREATE DATABASE nodemysql11', function(err,result) {
if(err){
console.log("error while creating database");
}
console.log('result: '+result);
res.send('database created..');
});
});
Try the below line and then run the .js file.
I assume u have done npm install mysql
mv ./node_modules/node-mysql/node_modules/* ./node_modules/
I am learning to develop server on node-js and have developed a basic get function which retrieves data from MySQL DB hosted on a ubuntu server at digitalocean.
Here's my code:
const express = require('express')
const app = express()
const mysql = require('mysql')
const Client = require('ssh2').Client;
const ssh = new Client();
const db = new Promise(function(resolve, reject){
ssh.on('ready', function() {
ssh.forwardOut(
// source address, this can usually be any valid address
'localhost',
// source port, this can be any valid port number
3333,
// destination address (localhost here refers to the SSH server)
'xxx.xxx.xxx.xxx',
// destination port
22,
function (err, stream) {
if (err) throw err; // SSH error: can also send error in promise ex.
reject(err)
// use `sql` connection as usual
connection = mysql.createConnection({
host : '127.0.0.1',
user : 'user',
password : 'pass',
database: 'mysql',
stream: stream
});
// send connection back in variable depending on success or not
connection.connect(function(err){
if (!err) {
resolve(connection)
} else {
reject(err)
}
});
});
}).connect({
host: 'xxx.xxx.xxx.xxx', //IP address where DB is hosted
port: 22, //Port refering to the IP
username: 'user', //username to loginto the host
password: 'pass' //password to log into host
});
});
//Retrieve route
app.get('/users', (req, res) => {
//console.log("Fetching user with id: " + req.params.id)
const queryString = "SELECT * FROM user"
connection.query(queryString, (err, rows, fields) => {
if(err){
console.log("Failed to query " + err)
res.sendStatus(500)
return
}
console.log("Fetch Succesful")
res.json(rows)
})
})
app.listen(3000, () => {
console.log("Server is up and listerning on port 3000")
})
When I run this code on my local machine it is able to connect to external DB and fetch the data. I have created another server at digitalocean and hosted the same code. However upon running it I get error at connection stating: UnhandledPromiseRejectionWarning: Error: connect ECONNREFUSED 127.0.0.1:3306
I tried various solutions available on the platform but could not suceed.
I have written the code accoring to the documentation but still clueless what's causing the error.
Thank You.
I'm getting error :
error:Error: Handshake inactivity timeout
I connected mysql to node by like this.
Install mysql
npm install mysql
var mysql = require('mysql');
let connection = mysql.createConnection({
host: 'localhost',
user: 'root',
port: '8888', /* port on which phpmyadmin run */
password: 'root',
database: 'dbname',
socketPath: '/Applications/MAMP/tmp/mysql/mysql.sock' //for mac and linux
});
connection.connect(function(err) {
if (err) {
return console.error('error: ' + err.message);
}
console.log('Connected to the MySQL server.');
});
You can use node-mysql, It very easy to use. I have used once, Here is the 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();
Use Connection Pool:
var mysql = require('mysql');
var pool = mysql.createPool({
host : 'example.org',
user : 'bob',
password : 'secret'
});
pool.getConnection(function(err, connection) {
// Use the connection
connection.query( 'SELECT something FROM sometable', function(err, rows) {
// And done with the connection.
connection.release();
// Don't use the connection here, it has been returned to the pool.
});
});