Cannot connect to mysql using Node js - mysql

I am trying to connect to mysql but I am getting the following error :
"Error: ER_ACCESS_DENIED_ERROR: Access denied for user ' root'#'localhost' (using password: YES)"
But when I connect using mysql command line client I am able to connect to mysql.
Here is my config.js file where I have defined the connectivity settings :
//config.js
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
port : '3306',
user : ' root',
password : 'root',
database : 'world'
});
module.exports = connection;
I am trying to connect to the db in this file :
// userController.js
var jwt = require('jwt-simple');
var connection = require("../config.js");
var auth = {
getAll: function(req, res) {
console.log("in user comtroller");
console.log(connection);
connection.connect(function(err) {
// connected! (unless `err` is set)
if(err){
console.log("Failed to connect to mysql. Error : "+err);
}
else{
console.log("connection Successful..!!");
}
});
res.send("going good");
}
}
module.exports = auth;

Related

How to connect mysql with nodejs

I want to connect my database with nodejs but it's not connecting and giving an Error: connect ETIMEDOUT.
My code is...
var con = mysql.createConnection({
host: hostname,
user: user,
password: pass,
database: database_name,
});
con.connect(function (error) {
if (error) console.log("Not Connected: " + error);
else console.log("connected");
});
const mysql = require('mysql');
const dbPool = mysql.createPool({
connectionLimit : 10,
port : 'port of your Db',
host : 'host of your Db,
user : 'user of your Db,
password : 'password of your Db,
database : 'database name,
dateStrings : true,
debug : false
});

Error when connecting mysql database with node js

I am using Node JS and I am trying to connect to a mysql database. It keeps getting disconnected.When I run npm start,error shows as follows
D:\face-api.js\face-api.js\examples\FaceLogInBackend\app.js:26
app.use( bodyParser.json() ); // to support JSON-encoded bodies
^
TypeError: Cannot read property 'use' of undefined
at Object. (D:\face-api.js\face-api.js\examples\FaceLogInBackend\app.js:26:5)
at Module._compile (internal/modules/cjs/loader.js:776:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:787:10)
Code in app.js is as belows
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'bookstore'
});
connection.connect(function(err) {
if (err) throw err
console.log('You are now connected...')
})
You need this
var mysql = require('mysql');
// instead of storing the result in a variable, just make the connection,
mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'bookstore'
});
// now connect to mysql
mysql.connect(function(err) {
if (err) throw err
console.log('You are now connected...')
})
First off check you have something like this declared on top of file
var app = express();
you can use the below code to connect to the MySQL. It works fine.
const express = require('express'),
app = express(),
bodyParser = require('body-parser');
port = process.env.PORT || 3000;
const mysql = require('mysql');
// connection configurations
const connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'bookstore'
});
// connect to database
connection.connect(function(err) {
if (err) throw err
console.log('You are now connected...')
})
app.listen(port);
console.log('API server started on: ' + port);
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

Error connecting to MySQL from Node-JS server

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.

Failed to connect to localhost:1433 - connect ECONNREFUSED 127.0.0.1:1433

I'm trying to connect to my local MySql server from node.js/express application using mssql with following config:
// Database connection
var sql = require('mssql');
var config = {
user: 'db_user',
password: 'db_pass',
server: 'localhost',
database: 'project_db'
};
sql.connect(config, function (err) {
if (err) {
console.log(err);
}
});
I get this error:
{ [ConnectionError: Failed to connect to localhost:1433 - connect ECONNREFUSED 127.0.0.1:1433]
name: 'ConnectionError',
message: 'Failed to connect to localhost:1433 - connect ECONNREFUSED 127.0.0.1:1433',
code: 'ESOCKET' }
I know I have to enable TCP/IP connections for my local MySql server, but I can not find how to do it on OSX El Capitan. There is nothing like control panel with settings. That's all available at System Preferences > MySql:
Any ideas how to fix this, guys? Thanks for trying to help.
mssql and mysql are two very different things... You should use the node-mysql or some other mysql client library if you are going to be running mysql on your dev machine
https://github.com/felixge/node-mysql
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();

Change <username>#<computername> to <username>#localhost in node js application

I'm new to node js, I was trying a sample of connecting MySql with node. When I run the code I get
Error while performing Query.Error: ER_ACCESS_DENIED_ERROR:
Access denied for user <username>#<computername> (using password: YES)
The problem is when I connect to Mysql through workbench with localhost it succeeds but when I use < computername > it gives me the same error.
I added "mysql": "^2.5.4" dependency in package.json file.
So can anyone help me on how to change the default option from < computername > to localhost
index.js file
var app = express();
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'myusername',
password : 'mypassword',
database : 'mydb'
});
app.set('port', (process.env.PORT || 5000));
app.use(express.static(__dirname + '/public'));
app.get('/', function(request, response) {
connection.connect();
connection.query('SELECT * from projects', function(err, rows, fields) {
if (!err)
console.log('The solution is: ', rows);
else
console.log('Error while performing Query.' + err);
});
connection.end();
response.send('Hello World !');
});
app.listen(app.get('port'), function() {
console.log('Node app is running on port', app.get('port'));
});
Try using the IP for localhost instead of the string 'localhost' for the host. The default is 127.0.0.1
var connection = mysql.createConnection({
host : '127.0.0.1',
user : 'myusername',
password : 'mypassword',
database : 'mydb'
});
EDIT:
It seems that you actually are able to connect to MYSQL, but that your user is not allowed to use the chosen database. Ensure that the user you connect with can access the database, in your example 'mydb'.