Hi, I think this issue is similar to mine:
- Connect to MySQL
- End MySQL service (should not quit node script)
- Start MySQL service, Node reconnects to MySQL
- Query the DB -> FAIL (Cannot enqueue Query after fatal error.)
I solved this issue by recreating a new connection with the use of promises (q).
mysql-con.js
'use strict';
var config = require('./../config.js');
var colors = require('colors');
var mysql = require('mysql');
var q = require('q');
var MySQLConnection = {};
MySQLConnection.connect = function(){
var d = q.defer();
MySQLConnection.connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : 'password',
database : 'database'
});
MySQLConnection.connection.connect(function (err) {
if(err) {
console.log('Not connected '.red, err.toString().red, ' RETRYING...'.blue);
d.reject();
} else {
console.log('Connected to Mysql. Exporting..'.blue);
d.resolve(MySQLConnection.connection);
}
});
return d.promise;
};
module.exports = MySQLConnection;
mysqlAPI.js
var mysqlCon = require('./mysql-con.js');
mysqlCon.connect().then(function(con){
console.log('connected!');
mysql = con;
mysql.on('error', function (err, result) {
console.log('error occurred. Reconneting...'.purple);
mysqlAPI.reconnect();
});
mysql.query('SELECT 1 + 1 AS solution', function (err, results) {
if(err) console.log('err',err);
console.log('Works bro ',results);
});
});
mysqlAPI.reconnect = function(){
mysqlCon.connect().then(function(con){
console.log("connected. getting new reference");
mysql = con;
mysql.on('error', function (err, result) {
mysqlAPI.reconnect();
});
}, function (error) {
console.log("try again");
setTimeout(mysqlAPI.reconnect, 2000);
});
};
I hope this helps.
What does the error mean?
{ [Error: Cannot enqueue Query after fatal error.] code: 'PROTOCOL_ENQUEUE_AFTER_FATAL_ERROR', fatal: false }
This code works in my test file:
function handleDisconnect() {
objConn = mysql.createConnection(db_config); // Recreate the connection, since
// the old one cannot be reused.
objConn.connect(function(err) { // The server is either down
if(err) { // or restarting (takes a while sometimes).
console.log('error when connecting to db:', err.code);
setTimeout(handleDisconnect, 2000); // We introduce a delay before attempting to reconnect,
}else{
console.log('Connected to db!');
} // to avoid a hot loop, and to allow our node script to
}); // process asynchronous requests in the meantime.
// If you're also serving http, display a 503 error.
objConn.on('error', function(err) {
if(err.code === 'PROTOCOL_CONNECTION_LOST') { // Connection to the MySQL server is usually
handleDisconnect(); // lost due to either server restart, or a
}else{
throw err;
}
});
}
handleDisconnect();
megaLoop();
function megaLoop(){
objConn.query('SELECT u.`email` FROM `users` as u', function(err, rows) {
console.log(err);
console.log(rows);
});
setTimeout(megaLoop, 100);
}
But when I use the function in my Express App I get the error:
{ [Error: Cannot enqueue Query after fatal error.] code: 'PROTOCOL_ENQUEUE_AFTER_FATAL_ERROR', fatal: false }
Why does it work in my test and not my app?
Содержание
- Node js + Mysql : cannot enqueue because of fatal errors
- «PROTOCOL_ENQUEUE_AFTER_FATAL_ERROR» after connection was lost, recreated #900
- Comments
- Cannot enqueue query error after Database failover (AWS RDS MySQL Aurora) #7
- Comments
- Unable to log the fatal error, Cannot enqueue Query after fatal error #1478
- Comments
- Error: Cannot enqueue Quit after invoking quit #238
- Comments
Node js + Mysql : cannot enqueue because of fatal errors
I’m running a application with node js (more specifically express js) and I save some datas with a mysql client.
It perfectly works for some time with no issue but then all of suddden I get these erros:
Trace: Cannot enqueue Quit after fatal error. at Protocol._validateEnqueue (C:nodejstwelve-coiffurenode_modulesmysqllibprotocolProtocol.js:218:11) at Protocol._enqueue (C:nodejstwelve-coiffurenode_modulesmysqllibprotocolProtocol.js:135:13) at Protocol.quit (C:nodejstwelve-coiffurenode_modulesmysqllibprotocolProtocol.js:88:23) at PoolConnection.end (C:nodejstwelve-coiffurenode_modulesmysqllibConnection.js:255:18) at Pool._purgeConnection (C:nodejstwelve-coiffurenode_modulesmysqllibPool.js:259:16) at PoolConnection._removeFromPool (C:nodejstwelve-coiffurenode_modulesmysqllibPoolConnection.js:70:8) at PoolConnection. (C:nodejstwelve-coiffurenode_modulesmysqllibPoolConnection.js:29:12) at emitOne (events.js:77:13) at PoolConnection.emit (events.js:169:7) at PoolConnection.Connection._handleProtocolError (C:nodejstwelve-coiffurenode_modulesmysqllibConnection.js:439:8) Trace: Cannot enqueue Query after fatal error. at Protocol._validateEnqueue (C:nodejstwelve-coiffurenode_modulesmysqllibprotocolProtocol.js:218:11) at Protocol._enqueue (C:nodejstwelve-coiffurenode_modulesmysqllibprotocolProtocol.js:135:13) at PoolConnection.query (C:nodejstwelve-coiffurenode_modulesmysqllibConnection.js:214:25) at Object.fetchDatas (C:nodejstwelve-coiffurepublicjavascriptstwelvebase.js:94:12) at C:nodejstwelve-coiffureroutesindex.js:7:7 at Layer.handle [as handle_request] (C:nodejstwelve-coiffurenode_modulesexpresslibrouterlayer.js:95:5) at next (C:nodejstwelve-coiffurenode_modulesexpresslibrouterroute.js:131:13) at Route.dispatch (C:nodejstwelve-coiffurenode_modulesexpresslibrouterroute.js:112:3) at Layer.handle [as handle_request] (C:nodejstwelve-coiffurenode_modulesexpresslibrouterlayer.js:95:5) at C:nodejstwelve-coiffurenode_modulesexpresslibrouterindex.js:277:22 C:nodejstwelve-coiffurepublicjavascriptstwelvebase.js:26 throw(message); ^
Error: Cannot enqueue Query after fatal error. at Protocol._validateEnqueue (C:nodejstwelve-coiffurenode_modulesmysqllibprotocolProtocol.js:199:16) at Protocol._enqueue (C:nodejstwelve-coiffurenode_modulesmysqllibprotocolProtocol.js:135:13) at PoolConnection.query (C:nodejstwelve-coiffurenode_modulesmysqllibConnection.js:214:25) at Object.fetchDatas (C:nodejstwelve-coiffurepublicjavascriptstwelvebase.js:94:12) at C:nodejstwelve-coiffureroutesindex.js:7:7 at Layer.handle [as handle_request] (C:nodejstwelve-coiffurenode_modulesexpresslibrouterlayer.js:95:5) at next (C:nodejstwelve-coiffurenode_modulesexpresslibrouterroute.js:131:13) at Route.dispatch (C:nodejstwelve-coiffurenode_modulesexpresslibrouterroute.js:112:3) at Layer.handle [as handle_request] (C:nodejstwelve-coiffurenode_modulesexpresslibrouterlayer.js:95:5) at C:nodejstwelve-coiffurenode_modulesexpresslibrouterindex.js:277:22
The problem is that I really can’t find where the issue comes from in my code, and I don’t even know why sometimes in works and sometimes not.
Here is my code to start the database:
Of course I’m calling fetchDatas() from another file to get all the datas to display.
Источник
«PROTOCOL_ENQUEUE_AFTER_FATAL_ERROR» after connection was lost, recreated #900
I implemented some error handling in case the mysql connection breaks.
However after a disconnect I always get a «PROTOCOL_ENQUEUE_AFTER_FATAL_ERROR», even though a new connection should have been established.
When I kill the MySQL Server I get the expected output, I then get an on Connection Error output every two seconds until I restart the MySQL Server. So it’s safe to assume that there is a new connection.
However I get the «PROTOCOL_ENQUEUE_AFTER_FATAL_ERROR» when I try to query afterwards. Both If I have or have not queried while the Server was down.
Am I missing something or is this unexpected behavior?
The text was updated successfully, but these errors were encountered:
I know that when there are pending callbacks, the error is not emitted to the connection object, but when I just restart the server and a new connection is established, I should be able to query afterwards right?
I also added a call to handleDisconnect() when I get a «PROTOCOL_ENQUEUE_AFTER_FATAL_ERROR» in a callback, same behavior.
with authcheck.js:54:20 obv. being the line where I call connection.query(querystring, callback)
It is because your variable reassignment
depends. There are many places in your code that can be using the old reference and you didn’t show the full picture of your code. But, really, I’m not particularly going to help with this anti-pattern for re-establishing a lost connection. You need to use pooling (https://github.com/felixge/node-mysql#pooling-connections)
The error itself means that your code did connection.query after the connection ended, which would only happen in the example you posted above by holding references to the old connection variable. At that point, it’s not a MySQL library issue, but a understanding of how JavaScript works issue. You can always find out if your code is not getting the updated reference by adding console.dir(connection.threadId) above all your connection.query statements—after the disconnect they should print null for a bit and then change to a different number. If the number doesn’t change, you’ll need to fix how you’re holding variable references in JavaScript if you want to continue to use that pattern.
TL;DR use a pool and do not use the code you posted.
Источник
Cannot enqueue query error after Database failover (AWS RDS MySQL Aurora) #7
We migrated majority of our Lambda functions to use this library in our dev environment to give it a run and so far it has been working great. However, yesterday we faced an issue, which still continues to be an issue and I have no idea how to resolve this.
Approximately at noon on Sunday our dev RDS MySQL (Aurora provisioned instance) crashed, and then eventually failed over to the failover instance. The reason of the crash is still unknown but we are investigating, however it is worth mentioning that this is the first time the instance ever crashed in the past 1.5 years of continuous reliable usage. Once the failover was complete, we were able to connect to the DB and query normally, however, all the Lambda functions were now throwing this error (see below). This error, specifically started after the failover and also ALL Lambda functions that query our database seem to be facing this exact error as it reflected in Cloudwatch logs. We stopped and started the cluster, rebooted the cluster even hoping to resolve this issue but the error kept showing up and the API Gateway endpoints continued to return error. We looked in the database and there were no lingering sessions/processes to be found.
We ultimately switched over a couple of Lambda’s to our native code which didn’t use this library, but was using traditional MySQL js connection pool and handler callback, instead. Curiously enough, those functions happened to be working just fine (even with concurrent requests). Since then, we reverted back all of the Lambda functions to our previous version since none of our Lambda functions were operational at the time due to the error above, but I thought it would be worth raising this issue since I am not entirely certain what’s causing it.
The text was updated successfully, but these errors were encountered:
Источник
Unable to log the fatal error, Cannot enqueue Query after fatal error #1478
The following error is happening when I make 5 requests / second to one of our servers.
We are able to log this error, but we are not able to catch what the fatal error is? We are using pooling for reusing the existing connections and creating new connections.
I tried the following to trace the fatal error but no use.
- Kept console.trace() before each err.fatal=true in node-mysql module source code.
- Added following lines of code to debug why the fatal error is happening,
Can somebody help on solving this error?
The text was updated successfully, but these errors were encountered:
Added following lines of code to debug why the fatal error is happening,
I got to know that the fatal error is,
But, I’m handling error at the following places,
- Getting the connection from the pool.
- Running the query
Where am I’m missing to log this error?
same here but i am getting some time i am also trying to replicate issue,do you know how to replicate issue ?
as you know we can solve issue but for that we need to replicate issue but i am not able to replicate issue every time.
I think that’s because the connection was closed by the server. After that, you cannot use the connection variable anymore.
You must recreate a new one, in order to continue to do queries.
Here, what I use to create a connection, and handle some errors:
@bsurendrakumar did you solved issue ? can i know how did you solved it ? i think @flexbrane approach is perfect . i am trying to solve issue using @flexbrane approach .
@nirmalgoswami I’m not able to solve this issue. As we are in hurry to finish the project in less time, we shifted to node-mariasql module.
Actually, this was not the right answer. Here, the correct code:
Thanks for your reply
No problem, for once I can help!
Hi @bsurendrakumar , can you share the full code you are using? How often are you getting the connection from the pool? Only once, every time you make a query? Sometime in between? Also, you should be able to see the error if you attach an error event listener on the connection object you get from the pool.
Hello @dougwilson thanks for focus on this issue. except this issue your work is awesome related to this plugin. I have read most of comment over internet related to this issue and i know that this error come when we are using one connection all over project. I know solutions is either use new connection before every query(but it will take lots of code change in existing stable project so i am against it ) or use @flexbrane ‘s approach. can you please do some comment on @flexbrane ‘s approach ? it will be good to choose solution to solve this issue.
Hi @nirmalgoswami, this issue has of course been discussed many times. The only thing that is just an issue is just how folks are using this module, many times it’s from copy-and-paste from sources outside of this project, which is a hard thing to police, so it has dubious opinions.
The problem is that once your connection is closed, you have to get a new connection. There really isn’t any other answer. Why is that the answer? Well, there are many operations you do in MySQL that you need the guarantee that you are using the same connection. For example, if you setup a session variable in one query, and use it in the next, you need to be sure you are using the same connection. Transactions are the main issue around this: if you BEGIN TRANSACTION on a connection, you are expecting that all your next queries until COMMIT or ROLLBACK are actually part of that transaction. If you are silently reconnecting, then that goes out the window, unfortunately, and you end up with really, really weird bugs.
Now, that’s not to say that there are people who are just not using transactions, session state, functions like LAST_INSERT_ID() , etc., and for them, your solution works.
Источник
Error: Cannot enqueue Quit after invoking quit #238
I keep on getting this error although the migrations run smoothly. How do I get rid of this and whats the reason behind it ?
The text was updated successfully, but these errors were encountered:
Hi @gayanhewa
I can’t help you if you don’t specify what exactly the failure is plus, which version of node you use and a log from a run in the verbose mode (-v).
Also please add details about your configuration.
This is how the error looks like :
Output from the db-migration up -v
NPM Version — 1.4.28
DB-Migrate — ^0.9.7
Server : Ubuntu 14.04 -/ Vagrant instance.
Ok, in your last run you didn’t run into a failure. I must be able to reproduce this bug to fix it.
Cannot enqueue Query after fatal error. Sounds like there went something wrong just before, in the migration or the db connection itself.
Could you please also deliver your node.js version?
Can you provide me more to reproduce this? Migrations with which this error is raised for example?
How do I know for which migration this happened ? , I have a few migrations and it happens even if I run just one.
Does this happen with every of your migrations? Try up -count 1 and look if this happens to all migrations even if they’re started single.
Yes. if I use the flag -c 1 it will happen aswell , but just once.
Well I still can’t reproduce this, could you please post one of your migrations. Of course you should delete everything that’s maybe confidential.
I’m away for some hours now, so I wont answere from now on.
Please provide enough information to make it possible to anyone to reproduce your issue. Without the possibility to reproduce no one can help you and the bug keeps unsolved.
- Used configuration tweaks.
- How does db-migrate gets invoked
- The full log of the full run where the error occurs in verbose mode, also including the queries generated. Replace confidential informations if needed.
- Post your migrations
Also answere these common questions:
- Do you have used db-migrate before?
- Does this error exist in an earlier release?
Hi, Thank you for the help. Here is what I could gather from my findings :
The Error doesn’t result in a failure. Its more connected to node-mysql rather the db-migrate module.
I was able to come down to the point where , after the migration is processed and a onComplete call back attempts to close the connection with the db and if it is already close there will be an error popping out.
For now I can suppress the erros from here. But not ideal.
Could you show me this migration?
Normaly db-migrate shouldn’t execute this twice. And also shouldn’t write that much entries to the migrations table.
It definitely seems that you made a mistake in your migrations. I suspect you’re calling the callback multiple times, which you mustn’t do!
I do have the call back multiple times since within a migration I called createTable and addIndex
Источник
Issue
I have an application nodejs running on top of a pm2.
My application has a strange behavior where I can not identify the problem, for some time running, 3 4 or 5 days
the application when trying to do a simple login where it needs a connection with the database the following error occurs:
Can not enqueue Query after fatal error
I have done everything possible to try to identify the cause of this problem, and it has not been identified a drop in the database server.
Someone could try to help, maybe it’s the way that getting the connection to the bank is wrong.
Database connection configuration db.js
const mysql = require('mysql');
const connection = mysql.createConnection({
connectionLimit : 20,
host : '******',
port : 3306,
user : '******',
password : '******',
database : '******'
});
connection.connect(function(err) {
if (err) {
console.log('Conexão com banco ocorreu erro. ' + err + ' ' + err.code);
return;
}
console.log('Conexão com banco ok!');
});
module.exports = connection;
route usuario
var express = require('express');
var router = express.Router();
var usuarioController = require('../controllers/usuario-controller');
router.get('/find/:id', usuarioController.findUsuario);
module.exports = router;
usuarioController
var db = require('../models/db');
var usuarioController = {
findUsuario: function(req, res) {
var codigoPessoa = req.params.id;
var sql = "SELECT p.codigoPessoa As codigo, "+
" p.nome AS nome "+
" FROM tpessoa p, "+
" tusuario u "+
" WHERE p.codigoPessoa = u.codigoPessoa "+
" AND u.codigoPessoa = " + codigoPessoa;
db.query(sql, function (err, rows) {
if (err) {
var message = err.message;
return res.status(500).send(message);
} else {
res.status(200).json(rows);
}
});
},
};
module.exports = usuarioController;
Error
Error: Connection lost: The server closed the connection.
at Protocol.end (/home/softaction/apps_nodejs/node_modules/mysql/lib/protocol/Protocol.js:112:13)
at Socket.<anonymous> (/home/softaction/apps_nodejs/node_modules/mysql/lib/Connection.js:97:28)
at Socket.<anonymous> (/home/softaction/apps_nodejs/node_modules/mysql/lib/Connection.js:502:10)
at emitNone (events.js:111:20)
at Socket.emit (events.js:208:7)
at endReadableNT (_stream_readable.js:1064:12)
at args.(anonymous function) (/opt/nvm/versions/node/v8.11.3/lib/node_modules/pm2/node_modules/event-loop-inspector/index.js:138:29)
at _combinedTickCallback (internal/process/next_tick.js:138:11)
at process._tickCallback (internal/process/next_tick.js:180:9)
Error: Cannot enqueue Query after fatal error.
at Protocol._validateEnqueue (/home/softaction/apps_nodejs/node_modules/mysql/lib/protocol/Protocol.js:200:16)
at Protocol._enqueue (/home/softaction/apps_nodejs/node_modules/mysql/lib/protocol/Protocol.js:138:13)
at Connection.query (/home/softaction/apps_nodejs/node_modules/mysql/lib/Connection.js:200:25)
at Strategy._verify (/home/softaction/apps_nodejs/security/autenticacao.js:66:16)
at Strategy.authenticate (/home/softaction/apps_nodejs/node_modules/passport-local/lib/strategy.js:88:12)
at attempt (/home/softaction/apps_nodejs/node_modules/passport/lib/middleware/authenticate.js:361:16)
at authenticate (/home/softaction/apps_nodejs/node_modules/passport/lib/middleware/authenticate.js:362:7)
My database connection configuration file is in a separate folder in the project.
Example:
-app
--models
---db.js
--controllers
---usuario-controller.js
--routes
---usuario-route.js
Solution
The common way to handle this with seems to use a pool of connections.
You can see examples based on the same problem you have in this post. One of the answers there shows a way to override the query
method so that you don’t need to rewrite each call with getConnection
/release
.
You can probably test this with a local DB:
- start the DB
- start the server
- try a login (or a mocked route that queries something)
- ensure it works
- kill/restart the DB
- try the route again
- ensure you have the same error
- implement the solution based on the link above
- test again and check the problem is gone
Answered By – Stock Overflaw
This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0
Hi @Riddhi Thacker, it is difficult to provide any useful answer without seeing what code you have that is causing this issue.
Understanding how the node runtime on edge behaves might help you.
In Edge, when the proxy is first deployed, the node application is started and this then keeps running until the proxy is next redeployed. It is quite possible that you are creating the connections to mysql when the node application is loaded.
Probably after a while the connection is dropped due to inactivity and hence when you make a new API call after a long gap, you are getting this error.
To use this right it will be best if you create the connection whenever an API request is made i.e. maybe in the GET handler of your http / express module. This way a new connection will be created for every request and the connection can be dropped after returning the response.
Also, it will be a good idea to isolate the cause of the error by running the node code(s) in your desktop on a standalone node.js server. Leave it running there for a day or 2 and then make a call to the node app to see if you get the same error, or whether the error occurs only on the edge platform.
max155
- 69
- 15
-
#1
При запуске бота пишет:
Error: Cannot enqueue Query after fatal error.
at Protocol._validateEnqueue (/var/bot/node_modules/mysql/lib/protocol/Protocol.js:199:16)
at Protocol._enqueue (/var/bot/node_modules/mysql/lib/protocol/Protocol.js:135:13)
at Connection.query (/var/bot/node_modules/mysql/lib/Connection.js:201:25)
at checkDrop [as _repeat] (/var/bot/bot.js:149:8)
at wrapper [as _onTimeout] (timers.js:275:11)
at Timer.listOnTimeout (timers.js:92:15)
Nova-game
- 26
- 0
-
#2
При запуске бота пишет:
Error: Cannot enqueue Query after fatal error.
at Protocol._validateEnqueue (/var/bot/node_modules/mysql/lib/protocol/Protocol.js:199:16)
at Protocol._enqueue (/var/bot/node_modules/mysql/lib/protocol/Protocol.js:135:13)
at Connection.query (/var/bot/node_modules/mysql/lib/Connection.js:201:25)
at checkDrop [as _repeat] (/var/bot/bot.js:149:8)
at wrapper [as _onTimeout] (timers.js:275:11)
at Timer.listOnTimeout (timers.js:92:15)
Бота надо другого или попробуй переустановить модули
casper
- 14
- 0
-
#4
При запуске бота пишет:
Error: Cannot enqueue Query after fatal error.
at Protocol._validateEnqueue (/var/bot/node_modules/mysql/lib/protocol/Protocol.js:199:16)
at Protocol._enqueue (/var/bot/node_modules/mysql/lib/protocol/Protocol.js:135:13)
at Connection.query (/var/bot/node_modules/mysql/lib/Connection.js:201:25)
at checkDrop [as _repeat] (/var/bot/bot.js:149:8)
at wrapper [as _onTimeout] (timers.js:275:11)
at Timer.listOnTimeout (timers.js:92:15)
добавь в скайп помогу casper_1005
Introduction
This is another article about NodeJS application. The focus of this article is just to show how to solve the problem exist upon executing a NodeJS application. The problem is rising an error message as exist in the title of the article. The error message is R_DBACCESS_DENIED_ERROR: Access denied for user ‘db_user’@’%’ to database ‘db_master’. The error message has an additional information on it. So, it can vary on another depends on the environment. The variation exist in the name of the user, host source access and also the database name. The following is the full error message upon executing a NodeJS application :
[admin@10 db]$ node app.js Error: ER_DBACCESS_DENIED_ERROR: Access denied for user 'db_user'@'%' to database 'db_master' at Handshake.Sequence._packetToError (/home/admin/nodejs/db/node_modules/mysql/lib/protocol/sequences/Sequence.js:47:14) at Handshake.ErrorPacket (/home/admin/nodejs/db/node_modules/mysql/lib/protocol/sequences/Handshake.js:123:18) at Protocol._parsePacket (/home/admin/nodejs/db/node_modules/mysql/lib/protocol/Protocol.js:291:23) at Parser._parsePacket (/home/admin/nodejs/db/node_modules/mysql/lib/protocol/Parser.js:433:10) at Parser.write (/home/admin/nodejs/db/node_modules/mysql/lib/protocol/Parser.js:43:10) at Protocol.write (/home/admin/nodejs/db/node_modules/mysql/lib/protocol/Protocol.js:38:16) at Socket. (/home/admin/nodejs/db/node_modules/mysql/lib/Connection.js:88:28) at Socket. (/home/admin/nodejs/db/node_modules/mysql/lib/Connection.js:526:10) at Socket.emit (events.js:315:20) at addChunk (internal/streams/readable.js:309:12) -------------------- at Protocol._enqueue (/home/admin/nodejs/db/node_modules/mysql/lib/protocol/Protocol.js:144:48) at Protocol.handshake (/home/admin/nodejs/db/node_modules/mysql/lib/protocol/Protocol.js:51:23) at Connection.connect (/home/admin/nodejs/db/node_modules/mysql/lib/Connection.js:116:18) at /home/admin/nodejs/db/app.js:24:7 at Layer.handle [as handle_request] (/home/admin/nodejs/db/node_modules/express/lib/router/layer.js:95:5) at next (/home/admin/nodejs/db/node_modules/express/lib/router/route.js:137:13) at Route.dispatch (/home/admin/nodejs/db/node_modules/express/lib/router/route.js:112:3) at Layer.handle [as handle_request] (/home/admin/nodejs/db/node_modules/express/lib/router/layer.js:95:5) at /home/admin/nodejs/db/node_modules/express/lib/router/index.js:281:22 at Function.process_params (/home/admin/nodejs/db/node_modules/express/lib/router/index.js:335:12) { code: 'ER_DBACCESS_DENIED_ERROR', errno: 1044, sqlMessage: "Access denied for user 'db_user'@'%' to database 'db_master'", sqlState: '42000', fatal: true } /home/admin/nodejs/db/app.js:32 throw err; ^ Error: Cannot enqueue Query after fatal error. at Protocol._validateEnqueue (/home/admin/nodejs/db/node_modules/mysql/lib/protocol/Protocol.js:212:16) at Protocol._enqueue (/home/admin/nodejs/db/node_modules/mysql/lib/protocol/Protocol.js:138:13) at Connection.query (/home/admin/nodejs/db/node_modules/mysql/lib/Connection.js:198:25) at Handshake. (/home/admin/nodejs/db/app.js:30:8) at Handshake. (/home/admin/nodejs/db/node_modules/mysql/lib/Connection.js:526:10) at Handshake._callback (/home/admin/nodejs/db/node_modules/mysql/lib/Connection.js:488:16) at Handshake.Sequence.end (/home/admin/nodejs/db/node_modules/mysql/lib/protocol/sequences/Sequence.js:83:24) at Handshake.ErrorPacket (/home/admin/nodejs/db/node_modules/mysql/lib/protocol/sequences/Handshake.js:125:8) at Protocol._parsePacket (/home/admin/nodejs/db/node_modules/mysql/lib/protocol/Protocol.js:291:23) at Parser._parsePacket (/home/admin/nodejs/db/node_modules/mysql/lib/protocol/Parser.js:433:10) { code: 'PROTOCOL_ENQUEUE_AFTER_FATAL_ERROR', fatal: false } [admin@10 db]$
The following is the content of the file with the name of ‘app.js’ :
const express = require("express"); const mysql = require("mysql"); const app = express(); app.get("/",(req,res) => res.send("Hello World !")); app.listen(3001); const con = mysql.createConnection({ host: "10.0.2.2", user : "db_user", password : "password", database : "db_master" }); app.post("/db",(req, res) => { try { con.connect(function(err){ if(err) console.debug(err); else console.log("Connected !"); }); } catch(err) { console.error(err.message); res.status(500).send("Server Error !"); } });
The above content file is actually a script for connecting to a host machine with the IP Address of ‘10.0.2.2’. After activating the NodeJS application, simulating the HTTP Post request using Postman application to access the address of ‘localhost:3001/db from the host machine. Accesing port 3001 from the host machine to the guest machine is possible. Check the article with the title of ‘How to Add Port Forwarding Rule to access NodeJS Service of Guest Machine running in VirtualBox Manager from Host Machine’ in this link. So, the execution of the NodeJS script actually exist in a guest machine or a virtual server. The guest machine is running in a VirtualBox application.
Solving the Problem
According to the description in the introduction, the problem is the privilege access. The reason is because the error message is showing it clearly. Clearly, the error message is : Access denied for user ‘db_user’@’%’ to database ‘db_master’. So, the problem exist in the absence of the privilege for ‘db_user’ to access the ‘db_master’ database. The following are the steps to solve it :
1. Check directly using MySQL client available in the guest machine or the virtual server where the execution of the NodeJS application occur. Try to connect to the MySQL database exist in the host machine as follows :
[admin@10 db]$ mysql -udb_user -p -h 10.0.2.2 db_master Enter password: ERROR 1044 (42000): Access denied for user 'db_user'@'%' to database 'db_master' [admin@10 db]$
2. Apparently, as exist in the above output command execution, it fails to connect. So, access MySQL Database Server in the host machine using any access available as follows :
[admin@10 db]$ mysql -uroot -p -h 10.0.2.2 Enter password: Welcome to the MySQL monitor. Commands end with ; or g. Your MySQL connection id is 160 Server version: 8.0.19 MySQL Community Server - GPL Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved. Oracle is a registered trademark of Oracle Corporation and/or its affiliates. Other names may be trademarks of their respective owners. Type 'help;' or 'h' for help. Type 'c' to clear the current input statement. mysql>
3. Next, after successfully logging in to MySQL Database Server, execute a query. The query execution in the MySQL Command Prompt is for granting access as follows :
mysql> use mysql Reading table information for completion of table and column names You can turn off this feature to get a quicker startup with -A Database changed mysql> grant all on db_master.* to 'db_user'@'%'; Query OK, 0 rows affected (0.38 sec) mysql> flush privileges; Query OK, 0 rows affected (0.14 sec) mysql>
4. After granting access in the previous step, just try again to access MySQL Database Server as follows :
[admin@10 db]$ mysql -udb_user -p -h 10.0.2.2 db_master Enter password: Reading table information for completion of table and column names You can turn off this feature to get a quicker startup with -A Welcome to the MySQL monitor. Commands end with ; or g. Your MySQL connection id is 162 Server version: 8.0.19 MySQL Community Server - GPL Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved. Oracle is a registered trademark of Oracle Corporation and/or its affiliates. Other names may be trademarks of their respective owners. Type 'help;' or 'h' for help. Type 'c' to clear the current input statement. mysql>
5. Finally, since the access directly from MySQL client is a success, try to execute the NodeJS application once more as follows :
[admin@10 db]$ node app.js Connected !