I have deployed my app on heroku..but the problem is ,it is giving this error
Unhandled rejection SequelizeConnectionRefusedError: connect ECONNREFUSED 127.0.0.1:3306
my config.js file-
module.exports={
port:process.env.PORT || 8082,
production: {
use_env_variable: process.env.DATABASE_URL
},
authentication:{
jwtSecret: process.env.JWT_SECRET|| 'secret'
}
}
my database connection file-
const Sequelize=require('sequelize')
const config=require('../config/config')
let sequelize=null;
if(process.env.DATABASE_URL){
sequelize=new Sequelize(config.production.use_env_variable,{dialect:'mysql'})
}
else{
sequelize=new Sequelize('bloggy','root','12345678',{dialect:'mysql',host:'localhost'})
}
module.exports=sequelize
I am not understanding why it is throwing that error.. it was working fine locally?
can anyone please help?
Ensure that in Heroku you have set the DATABASE_URL in environment variable b running Heroku config:set DATABASE_URL=<your database url>. This will ensure the if statement will return true and execute the first block
Related
Whenever i try to connect my express.js app to the node server. I get an error(see below console message).
Earlier, before dockerizing my app everything used to run smoothly but after creating my mysql-image-container(docker) and running mysql through docker everything went well. But now, when i try to connect my app with SQL server and not through the docker-container i get the following error
(node:22136) UnhandledPromiseRejectionWarning: SequelizeAccessDeniedError: Access denied for user 'root'#'localhost' (using password: YES)
at ConnectionManager.connect (C:\Users\A\ARISE1\node_modules\sequelize\lib\dialects\mysql\connection-manager.js:94:17)
at processTicksAndRejections (internal/process/task_queues.js:95:5)
at async ConnectionManager._connect (C:\Users\A\ARISE1\node_modules\sequelize\lib\dialects\abstract\connection-manager.js:220:24)
at async C:\Users\A\ARISE1\node_modules\sequelize\lib\dialects\abstract\connection-manager.js:174:32
at async ConnectionManager.getConnection (C:\Users\A\ARISE1\node_modules\sequelize\lib\dialects\abstract\connection-manager.js:197:7)
at async C:\Users\A\ARISE1\node_modules\sequelize\lib\sequelize.js:304:26
at async MySQLQueryInterface.tableExists (C:\Users\A\ARISE1\node_modules\sequelize\lib\dialects\abstract\query-interface.js:102:17)
at async Function.sync (C:\Users\A\ARISE1\node_modules\sequelize\lib\model.js:939:21)
at async Sequelize.sync (C:\Users\A\ARISE1\node_modules\sequelize\lib\sequelize.js:376:9)
(Use node --trace-warnings ... to show where the warning was created)
(node:22136) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag --unhandled-rejections=strict (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:22136) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
I have tried deleting docker file, mysql-image-container(from docker) but am still unable to connect my app with local mysql server. And now if i even try to connect to my database through SQL-command line, i am unable to do so, even with correct credentials. Though I'm able to connect to the database through MySQL Workbench.
The docker command used to build-image/run the container is:
docker run -p 3306:3306 --name nodejs-mysql -e MYSQL_ROOT_PASSWORD=pass -e MYSQL_DATABASE=database -d mysql:5.7
before this, i used to right-click on the dockerfile and choose build image option.
I didn't completely understood the contents of Dockerfile and so i mixed some code from online sources.
Any help would be well appreciated.
const sequelize = new Sequelize( username, password, database, {
host: host,
dialect: dialect
});
Instead of above, it should be this
const sequelize = new Sequelize( database, username, password, {
host: host,
dialect: dialect
});
Please share your code.
Also see the the code below on how you establish a connection
const { Sequelize,DataTypes } = require('sequelize');
const config={
HOST:"localhost",// you can replace this with the url of where your server is hosted or an ip adress
USER:"root",
PASSWORD:"yourpassword",
DB:"yourDb",
dialect:"mysql",//sqlite, mariadb
pool:{
max:5,
min:0,
acquire:30000,
idle:10000
}
const sequelize= new Sequelize(
config.DB,
config.USER,
config.PASSWORD,
{
host:config.HOST,
dialect:config.dialect,
operatorAliases:false,
pool:{
max:config.pool.max,
min:config.pool.min,
acquire:config.pool.acquire,
idle:config.pool.idle
}
}
)
try {
await sequelize.authenticate();
console.log('Connection has been established successfully.');
} catch (error) {
console.error('Unable to connect to the database:', error);
}
I am testing my db connection using mocha module of nodejs and the test is passing locally.
describe('Access to DB', function(){
describe('#fail', function(){
it('should return -1 because wrong credentials', function(done){
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'head',
database: 'head'
});
connection.connect(done);
});
})
});
./node_modules/.bin/mocha ./test/test.js tests pass when I run this command.
But when I run my job using jenkins. The test fails with error:
Access to DB #fail should return -1 because wrong credentials: [0m[31m Error: connect ECONNREFUSED 127.0.0.1:3306[0m[90m at TCPConnectWrap.afterConnect [as oncomplete]
My jenkins is instaled in different server and Node app in different one. I am comunication between them with SHA keys. Everything is working except for this test. mysql is not installed in jenkins server. Could that be the reason.
I'd like to connect to a MySQL database using Sequelizer. Right now, I'm getting a Connection Refused Error.
To access the database, I have to SSH in. According to Mick Hansen here: https://github.com/sequelize/sequelize/issues/3753, one way to SSH in is to use tunnel-ssh to establish the tunnel, then initiate Sequelizer.
My (unsuccessful) approach so far has been to initiate the tunnel, then when the tunnel opens, test whether Sequelizer has authenticated.
Update
Host: DigitalOcean
CLI Success: I can 1) ssh into digitalocean server 2) login into mysql from the server and 3) access all database information as the root user.
Sequel Pro: I can also log into the database using Sequel Pro.
MySQL 127.0.0.1:3306: Based on the mysql/my.cnf file, the port is 3306 and the bind-address is 127.0.0.1. The config file also says instead of skip-networking, the default is to listen only on localhost, if that's relevant.
socketPath -> Error Connection Switching from TCP to socket seems to sometimes work for this type of problem, but when I tried it, I continued to get a connection refused error.
2 Error Types - "All Configured Authentication Methods Failed" and "Error Connection Refused"
Thanks for the help!
Code:
// sequelize config
var sequelize = new Sequelize('database', 'user', 'pass', {
host: '127.0.0.1',
dialect: 'mysql',
port: 3306,
pool: {
max: 10,
min: 0,
idle: 20000
}
});
// tunnel config
var config = {
user:'user',
host:'sshHost',
port:22,
dstHost:'127.0.0.1',
dstPort:3306,
srcHost:'127.0.0.1',
srcPort:3306,
localHost:'127.0.0.1',
localPort: 3306,
privateKey:require('fs').readFileSync('/path/to/key')
};
var tunnel = require('tunnel-ssh');
// initiate tunnel
tunnel(config, function (error, server) {
//....
if(error) {
console.error(error);
} else {
console.log('server:', server);
// test sequelize connection
sequelize
.authenticate()
.then(function(err) {
console.log('Connection established');
})
.catch(function(err) {
console.error('unable to establish connection', err);
})
}
})
When my config is set to the object above, I get an "All configuration methods failed error".
If I change my config to the below, I get a "Sequelize Error Connection Refused" error.
// tunnel config
var config = {
user:'user',
host:'sshHost',
port:22,
dstHost:'127.0.0.1',
dstPort:3306,
//srcHost:'127.0.0.1',
//srcPort:3306,
//localHost:'127.0.0.1',
//localPort: 3306,
privateKey:require('fs').readFileSync('/path/to/key')
};
localPort is the port listening on your local system. Currently you have it defined as 27000 but your Sequelize config is set to 3306.
I have no trouble connecting to the live database locally using port forwarding, but when we go to connect from the openshift gear, we get errors. Let me begin with the code:
Here is the connection variable
var connectionpool = mysql.createPool({
host : process.env.OPENSHIFT_MYSQL_DB_HOST,
port : process.env.OPENSHIFT_MYSQL_DB_PORT,
user : process.env.OPENSHIFT_MYSQL_DB_USERNAME,
password : process.env.OPENSHIFT_MYSQL_DB_PASSWORD,
database : 'stembuds',
socket : process.env.OPENSHIFT_MYSQL_DB_SOCKET
});
Here is an example of a query:
app.get('/answerDB/:course?/:answerID?', function(req, res){
var course = req.param('course');
var answerID = req.param('answerID');
connectionpool.getConnection(function(err, connection){
if(err){
console.error('CONNECTION error: ',err);
res.statusCode = 503;
res.send({
result: 'error',
err: err.code
});
}
if (course === undefined && answerID === undefined) {
connection.query('SELECT * FROM questions WHERE counter = 0', function(err, rows, fields){
if (err) {
console.error(err);
res.statusCode = 500;
res.send({
result: 'error',
err: err.code
});
}
for(var i in rows){
var newCourse = rows[i].course;
newCourse = courses[newCourse];
rows[i].course = newCourse;
}
res.send(rows);
connection.release();
});
}
Here are some errors we receive.
First is an error in the console of Chrome:
GET http://**.rhcloud.com/answerDB 503 (Service Temporarily Unavailable)
But sometimes we get a proxy error:
GET http://**.rhcloud.com/exploreDB 502 (Proxy Error)
Additionally, I have been running the command rhc tail -a nodejs and here is the error I am receiving
CONNECTION error: { [Error: ER_ACCESS_DENIED_ERROR: Access denied for user 'adminMYXaSuf'#'127.11.28.130' (using password: YES)]
code: 'ER_ACCESS_DENIED_ERROR',
errno: 1045,
sqlState: '28000',
fatal: true }
TypeError: Cannot call method 'query' of undefined
at /var/lib/openshift/5303aee55973ca4092000084/app-root/runtime/repo/routes/site.js:172:15
at Pool.<anonymous> (/var/lib/openshift/5303aee55973ca4092000084/app- root/runtime/repo/node_modules/mysql/lib/Pool.js:49:16)
at Handshake.Sequence.end (/var/lib/openshift/5303aee55973ca4092000084/app-root/runtime/repo/node_modules/mysql/lib/protocol/sequences/Sequence.js:78:24)
at Handshake.ErrorPacket (/var/lib/openshift/5303aee55973ca4092000084/app-root/runtime/repo/node_modules/mysql/lib/protocol/sequences/Handshake.js:93:8)
at Protocol._parsePacket (/var/lib/openshift/5303aee55973ca4092000084/app-root/runtime/repo/node_modules/mysql/lib/protocol/Protocol.js:202:24)
at Parser.write (/var/lib/openshift/5303aee55973ca4092000084/app-root/runtime/repo/node_modules/mysql/lib/protocol/Parser.js:62:12)
at Protocol.write (/var/lib/openshift/5303aee55973ca4092000084/app-root/runtime/repo/node_modules/mysql/lib/protocol/Protocol.js:37:16)
at Socket.<anonymous> (/var/lib/openshift/5303aee55973ca4092000084/app-root/runtime/repo/node_modules/mysql/lib/Connection.js:72:28)
at Socket.EventEmitter.emit (events.js:95:17)
at Socket.<anonymous> (_stream_readable.js:720:14)
Now it says cannot call method query of undefined. We thought that was strange, so we changed 'connection.query' to 'connectionpool.query' and it then told us that it cannot call method release of undefined. So we changed 'connection.release()' to 'connectionpool.release()' and it told us that the object # has no method release. So I am taking that part of the error with a grain of salt.
We have no idea why it wont connect. Any information would be greatly appreciated - Thanks.
If your application code works locally while connecting to your remote OpenShift-hosted DB (using rhc port-forward), then I would suspect that your app may have some undocumented dependencies.
It could be that you've installed something locally (or globally) in your dev environment, without including that dep in your app's package.json file.
Make sure that everything your app needs in order to run in a fresh environment is included in your app's package.json file before pushing it to OpenShift.
npm install my_dependency --save
I've written up some additional notes that might be useful for testing locally with a port-forwarded connection to an OpenShift-hosted DB: https://www.openshift.com/blogs/set-up-local-access-to-openshift-hosted-services-with-port-forwarding
Did you create that database name? It should be the name of your application. You can use the OPENSHIFT_APP_NAME environment variable for your database name. Can you ssh into your gear and connect to mysql without any issues? Also, are you trying to connect to the database on your openshift gear from your local machine or from your openshift gear?
I have the next code in a js file:
var mysql = require('mysql');
var TEST_DATABASE = 'nodejs_mysql_test';
var TEST_TABLE = 'test';
var client = mysql.createClient({
user: 'root',
password: 'root',
});
client.query('CREATE DATABASE '+TEST_DATABASE, function(err) {
if (err && err.number != mysql.ERROR_DB_CREATE_EXISTS) {
throw err;
}
});
But I get this error:
node.js:201
throw e; // process.nextTick error, or 'error' event on first tick
^
Error: connect ECONNREFUSED
at errnoException (net.js:632:11)
at Object.afterConnect [as oncomplete] (net.js:623:18)
As I understand it, this is a connection problem - but how do I solve it?
( I'm working on windows 7)
Thanks!!
I know two ways to solve it:
In mysql.conf, comment skip-networking.
Try to set the socket like this:
var client = mysql.createClient({
user: uuuu,
password: pppp,
host: '127.0.0.1',
port: '3306',
_socket: '/var/run/mysqld/mysqld.sock',});
I got this error when MySQL Server was not running.
I changed my configuration via Initialize Database in MySQL.PrefPane, the System Preferences tool for MySQL on OS X - to Use Legacy Password Encryption - to fix ER_NOT_SUPPORTED_AUTH_MODE.
This config change stopped MySQL Server and then I got ECONNREFUSED when I tried to connect to MySQL from node.js.
Fixed by restarting MySQL Server from the MySQL System Preferences tool.
Try to fix your defined port in mysql and your Node.js script.
You can define the mysqld port in the *.cnf file inside the mysql directory,
and you can define that port when you connect to MySQL in your Node.js script.
Something like this in the cnf file
port = 3306