When I send the first request after starting the server, it's okay.
But after updating the page (re-query), you receive an error:
app.get('/images', function(req, res, next) {
if (connection.state === 'disconnected'){
connection.connect();}
else {
}
var DATABASE='nodejsImage';
var results;
connection.query('use ' + DATABASE);
connection.query('SELECT `id`, `imagename`, `filename`, `speed`, `move` FROM `images` WHERE 1',
function (err, results, fields) {
if (err) return console.log("Error test") //throw err;
else {
console.log('Images list');
console.log('----------------------------------');
for (var i in results) {
var gadget = results[i];
console.log(gadget.id +': '+ gadget.imagename+': '+gadget.speed+': '+gadget.move);
}
res.render('imagelist', { title: 'Imagelist',listImages:results });
}
});
connection.end(); //разобраться с ошибкой позже!!!
});
Error message:
events.js:165
throw er; // Unhandled 'error' event
^
Error: Cannot enqueue Handshake after invoking quit.
at Protocol._validateEnqueue (E:\Dropbox\untitled5-upload-3\untitled5\node_modules\mysql\lib\protocol\Protocol.js:204:16)
at Protocol._enqueue (E:\Dropbox\untitled5-upload-3\untitled5\node_modules\mysql\lib\protocol\Protocol.js:139:13)
at Protocol.handshake (E:\Dropbox\untitled5-upload-3\untitled5\node_modules\mysql\lib\protocol\Protocol.js:52:23)
at Connection.connect (E:\Dropbox\untitled5-upload-3\untitled5\node_modules\mysql\lib\Connection.js:118:18)
at E:\Dropbox\untitled5-upload-3\untitled5\app.js:48:16
at Layer.handle [as handle_request] (E:\Dropbox\untitled5-upload-3\untitled5\node_modules\express\lib\router\layer.js:95:5)
at next (E:\Dropbox\untitled5-upload-3\untitled5\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (E:\Dropbox\untitled5-upload-3\untitled5\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (E:\Dropbox\untitled5-upload-3\untitled5\node_modules\express\lib\router\layer.js:95:5)
at E:\Dropbox\untitled5-upload-3\untitled5\node_modules\express\lib\router\index.js:281:22
Emitted 'error' event at:
at Connection._handleProtocolError (E:\Dropbox\untitled5-upload-3\untitled5\node_modules\mysql\lib\Connection.js:425:8)
at Protocol.emit (events.js:180:13)
at Protocol._delegateError (E:\Dropbox\untitled5-upload-3\untitled5\node_modules\mysql\lib\protocol\Protocol.js:392:10)
at Handshake.<anonymous> (E:\Dropbox\untitled5-upload-3\untitled5\node_modules\mysql\lib\protocol\Protocol.js:221:10)
at Handshake.emit (events.js:180:13)
at Handshake.Sequence.end (E:\Dropbox\untitled5-upload-3\untitled5\node_modules\mysql\lib\protocol\sequences\Sequence.js:83:12)
at E:\Dropbox\untitled5-upload-3\untitled5\node_modules\mysql\lib\protocol\Protocol.js:225:14
at process._tickCallback (internal/process/next_tick.js:112:11)
It are easy way to add pass items
to view.
var imageList = [];
// Connect to MySQL database.
var connection = getMySQLConnection();
connection.connect();
// Do the query to get data.
connection.query('SELECT * FROM images', function(err, rows, fields) {
if (err) {
res.status(500).json({"status_code": 500,"status_message": "internal server error"});
} else {
// Loop check on each row
for (var i = 0; i < rows.length; i++) {
// Create an object to save current row's data
var person = {
'id':rows[i].id,
'imagename':rows[i].imagename,
'filename':rows[i].filename,
'speed':rows[i].speed,
'move':rows[i].move
}
// Add object into array
imageList.push(person);
}
// Render index.pug page using array
res.render('imagelist', { title: 'Imagelist',listImages:imageList });
}
});
// Close the MySQL connection
connection.end();
Related
All the Solutions I found for this Problem don't work for me.
I'm just loading one Dataset and after approximate 150 Request I get this Error:
Error: Packets out of order. Got: 1 Expected: 0
at Parser._tryReadPacketHeader (C:\dev\node\webkoll\node_modules\mysql\lib\protocol\Parser.js:470:15)
at Parser.write (C:\dev\node\webkoll\node_modules\mysql\lib\protocol\Parser.js:33:29)
at Protocol.write (C:\dev\node\webkoll\node_modules\mysql\lib\protocol\Protocol.js:38:16)
at Socket.<anonymous> (C:\dev\node\webkoll\node_modules\mysql\lib\Connection.js:88:28)
at Socket.<anonymous> (C:\dev\node\webkoll\node_modules\mysql\lib\Connection.js:526:10)
at Socket.emit (events.js:223:5)
at addChunk (_stream_readable.js:309:12)
at readableAddChunk (_stream_readable.js:290:11)
at Socket.Readable.push (_stream_readable.js:224:10)
at TCP.onStreamRead (internal/stream_base_commons.js:181:23)
--------------------
at Protocol._enqueue (C:\dev\node\webkoll\node_modules\mysql\lib\protocol\Protocol.js:144:48)
at Protocol.handshake (C:\dev\node\webkoll\node_modules\mysql\lib\protocol\Protocol.js:51:23)
at PoolConnection.connect (C:\dev\node\webkoll\node_modules\mysql\lib\Connection.js:116:18)
at Pool.getConnection (C:\dev\node\webkoll\node_modules\mysql\lib\Pool.js:48:16)
at C:\dev\node\webkoll\dbHelper.js:35:22
at new Promise (<anonymous>)
at dbHelper.execQueryWithParams (C:\dev\node\webkoll\dbHelper.js:34:16)
at dbHelper.loadFinishedResultFlag (C:\dev\node\webkoll\dbHelper.js:68:21)
at C:\dev\node\webkoll\index.js:321:30
at Layer.handle [as handle_request] (C:\dev\node\webkoll\node_modules\express\lib\router\layer.js:95:5) { code: PROTOCOL_PACKETS_OUT_OF_ORDER', fatal: true}
I'm using node v12.14.1 and the npm package mysql v2.18.1.
I also set the max_allowed_packet to 1G but it did not help.
Here the Code i use to get the data:
class dbHelper {
constructor() {
const { host, user, password, database, connectionLimit } = config.db;
this.con = mysql.createPool({
connectionLimit,
host,
user,
password,
database
});
}
async execQueryWithParams(query, params) {
return new Promise((resolve, reject) => {
this.con.getConnection((err, connect) => {
if (err) {
console.log(err);
return reject(err)
}
connect.query(query, [params], (err, result) => {
if (err) {
return reject(err);
}
resolve(result);
})
})
});
}
I found the Problem.
After using the npm package mysql2 I got the error message: "Too many connections".
I dumbly initialized my class way to often, so after using just one instance everything worked fine.
Try to increase the MAX_Packet_Allowed Memory - it works in my case
It can be - your pool connection is lost. Try checking wether it is still up.
You are doing some minor mistake for define variable and function definition on proper ways..
const mysql = require('mysql');
const con = mysql.createConnection({
host : process.env.RDS_HOSTNAME,
user : process.env.RDS_USERNAME,
password : process.env.RDS_PASSWORD,
port : process.env.RDS_PORT,
database : process.env.RDS_DATABASE
});
exports.handler = (event, context, callback) => {
// allows for using callbacks as finish/error-handlers
context.callbackWaitsForEmptyEventLoop = false;
const sql = "select * from user_status";
con.query(sql, function (err, result) {
if (err) throw err;
console.log(result);
callback(null, result)
});
};
I am using the above code and now I m getting data from my RDS.🙂🙂
Note: you need to define your mysql credentials for host,user,password,port,database.
I am trying to create my first database with node.js but I cant't connect to the server.It gives me error 1061.I am absolutely new in creating databases and I have no idea where is my mistake.Can someone help me?
Thank you!
Here is my code:
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "mydb"
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
con.query("SELECT * FROM customers", function (err, result, fields) {
if (err) throw err;
console.log(result);
});
});
const http = require('http');
var qs = require('querystring');
var url = require('url');
const server = http.createServer();
server.on('request', (request, response) => {
var url_parts = url.parse(request.url, true);
var query = url_parts.query;
console.log(query);
var body = '';
response.setHeader("Access-Control-Allow-Origin", "*");
request.on('data', (chunk) => {
body += chunk;
}).on('end', () => {
var post = qs.parse(body);
console.log(post);
if(query.command == "register") {
con.query("INSERT INTO customers (name, email, password)
VALUES(?,?,?)", [post.name, post.email, post.password], function (err, result, fields) {
if (err) throw err;
console.log(result);
});
}
response.statusCode = 200;
response.end();
});
});
server.listen(8080);
Here is the Console output:
C:\Users\HP>node server.js
C:\Users\HP\server.js:11
if (err) throw err;
^
Error: connect ECONNREFUSED 127.0.0.1:3306
at Object._errnoException (util.js:1031:13)
at _exceptionWithHostPort (util.js:1052:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1195:14)
--------------------
at Protocol._enqueue (C:\Users\HP\node_modules\mysql\lib\protocol\Protocol.js:145:48)
at Protocol.handshake (C:\Users\HP\node_modules\mysql\lib\protocol\Protocol.js:52:23)
at Connection.connect (C:\Users\HP\node_modules\mysql\lib\Connection.js:130:18)
at Object.<anonymous> (C:\Users\HP\server.js:10:5)
at Module._compile (module.js:641:30)
at Object.Module._extensions..js (module.js:652:10)
at Module.load (module.js:560:32)
at tryModuleLoad (module.js:503:12)
at Function.Module._load (module.js:495:3)
at Function.Module.runMain (module.js:682:10)
This error means that node.js can't connect to your MySQL server.
Most likely your MySQL server not started at all.
I am developing an application with front end as angular and back end is node js, listing some values from database and send to node js .It shows some error like circular structure is there any way to override or any other option to response send back to my client side.
Node js server instance is :
app.post('/countrylist', function(req, res) {
var urlMataData = {
request : req,
responce:res
};
amqHandler.sendToAMQPServer(serialize.serialize(urlMataData),amqpConnection, 'countrylist' ,function(err,result){
console.log("callback value==>" + result)
});
amqHandler.reciveData(amqpConnection,'countrylist' ,function(err,data){
if(!err ){
console.log("am reciving request")
httpRequestHandler. makeHttpRequest(data,'countrylist', function(row){
console.log("CountryType==>"+ JSON.parse( row));
//res.json(row);
});
} else {
res.json(err);
}
});
});
Request handler is :
var countryList = function(req, res, next) {
query = 'SELECT id_country, country FROM edu.tbl_country';
database.getConnection(function (err, con) {
if(!err){
con.query(query, function(err,row) {
console.log("row type:"+ typeof row );
//res.contentType('application/json');
res.json(JSON.stringify(row));
});
}
});
};
Error
var body = JSON.stringify(val, replacer, spaces);
^
TypeError: Converting circular structure to JSON
at Object.stringify (native)
at ServerResponse.json (/root/nodejsworkspace/EDU/rabitmq/node_modules/express/lib/response.js:228:19)
at ClientRequest.<anonymous> (/root/nodejsworkspace/EDU/rabitmq/AMQPServer.js:116:23)
at ClientRequest.g (events.js:273:16)
at emitOne (events.js:90:13)
at ClientRequest.emit (events.js:182:7)
at HTTPParser.parserOnIncomingClient [as onIncoming] (_http_client.js:469:21)
at HTTPParser.parserOnHeadersComplete (_http_common.js:103:23)
at Socket.socketOnData (_http_client.js:359:20)
at emitOne (events.js:90:13)
I am studying nodejs with mysql and I am following this example:
https://codeforgeek.com/2015/03/real-time-app-socket-io/
But when I run the code and try to add a new data I got these errors:
C:\wamp\www\Node_JS\mysql>node server.js
Listening on 3000
A user is connected!
A user is connected!
C:\wamp\www\Node_JS\mysql\node_modules\mysql\lib\protocol\Parser.js:82
throw err;
^
TypeError: Cannot read property 'release' of undefined
at C:\wamp\www\Node_JS\mysql\server.js:37:14
at Handshake.onConnect (C:\wamp\www\Node_JS\mysql\node_modules\mysql\lib\Pool.js:54:9)
at Handshake.Sequence.end (C:\wamp\www\Node_JS\mysql\node_modules\mysql\lib\protocol\sequences\Sequence.js:96:24)
at Handshake.ErrorPacket (C:\wamp\www\Node_JS\mysql\node_modules\mysql\lib\protocol\sequences\Handshake.js:103:8)
at Protocol._parsePacket (C:\wamp\www\Node_JS\mysql\node_modules\mysql\lib\protocol\Protocol.js:274:23)
at Parser.write (C:\wamp\www\Node_JS\mysql\node_modules\mysql\lib\protocol\Parser.js:77:12)
at Protocol.write (C:\wamp\www\Node_JS\mysql\node_modules\mysql\lib\protocol\Protocol.js:39:16)
at Socket.<anonymous> (C:\wamp\www\Node_JS\mysql\node_modules\mysql\lib\Connection.js:96:28)
at Socket.emit (events.js:107:17)
at readableAddChunk (_stream_readable.js:163:16)
Here's my code in the server.js
var app = require('express')();
var mysql = require('mysql');
var http = require('http').Server(app);
var io = require('socket.io')(http);
/** mysql pool connection **/
var pool = mysql.createPool({
connectionLimit : 100,
host : 'localhost',
user : 'root',
password : '',
database : 'fbstatus',
debug : false
});
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
/** this will run automatically if server received a connection **/
io.on('connection', function(socket){
console.log('A user is connected!');
socket.on('status added', function(status){
add_status(status, function(res){
if(res) {
io.emit('refresh feed', status);
} else {
io.emit('error');
}
});
});
});
var add_status = function(status, callback) {
pool.getConnection(function(err, connection){
if(err) {
connection.release();
callback(false);
return;
}
connection.query("INSERT INTO fb_status VALUES('" + status + "')", function(err, rows){
connection.release();
if(!err) {
callback(true);
}
});
connection.on('error', function(err){
callback(false);
return;
});
});
}
http.listen(3000, function(){
console.log("Listening on 3000");
});
I dont know whats the problem about my code. Can you help me?
if(err) {
connection.release();
callback(false);
return;
}
here, if err you will not get a connection.
the mysql/node.js appears to connect then i "think" there may be a problem with the query event logic. Here's the code and error. I also have a separate/similar problem with postreSQL. I install npmed both in the same directory.
ryan#\Ryan:~/Desktop/node/datastores$ node MySQL
connection::connected
/home/ryan/Desktop/node/datastores/MySQL.js:20
if (err) throw err;
^
Error: connect ECONNREFUSED
at errnoException (net.js:901:11)
at Object.afterConnect [as oncomplete] (net.js:892:19)
--------------------
at Protocol._enqueue (/home/ryan/Desktop/node/node_modules/mysql/lib/protocol/Protocol.js:135:48)
at Protocol.handshake (/home/ryan/Desktop/node/node_modules/mysql/lib/protocol/Protocol.js:52:41)
at Connection.connect (/home/ryan/Desktop/node/node_modules/mysql/lib/Connection.js:123:18)
at Object.<anonymous> (/home/ryan/Desktop/node/datastores/MySQL.js:15:12)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
this is my server/mysql logic
var mysql = require('mysql');
var connectionConfig = {
host: 'localhost',
user: 'root',
password: '',
database: 'sakila'
};
var connection = mysql.createConnection( connectionConfig);
connection.connect(function(err) {
console.log('connection::connected');
});
connection.query('SELECT * FROM actor', function(err, rows, fields) {
if (err) throw err;
rows.forEach(function(row) {
console.log(row.first_name, row.last_name);
});
});
var actor = { first_name: 'Wil', last_name: 'Wheaton' };
connection.query('INSERT INTO actor SET ?', actor, function(err, results) {
if (err) throw err;
console.log(results);
});
connection.end(function(err) {
console.log('connection::end');
});
heres postre logic
var pg = require('pg');
var connectionString = 'postgres://ryan#localhost/postgres';
var client = new pg.Client(connectionString);
client.connect(function(err) {
if (err) throw err;
client.query('SELECT NOW() AS "THE TIME"', function( err, result ) {
if (err) throw err;
console.log(result.rows[0]);
client.end();
});
});
heres error
ryan#\Ryan:~/Desktop/node/datastores$ node postreSQL
/home/ryan/Desktop/node/datastores/postreSQL.js:8
if (err) throw err;
^
Error: connect ECONNREFUSED
at errnoException (net.js:901:11)
at Object.afterConnect [as oncomplete] (net.js:892:19)
Your password seems to be empty in both connections.
You need to get the connection details for the database from your devOps / SysAdmin / whoever created it.
Ask for the hostname, port, user and password, and schema name; then put those in your init object:
// MySQL:
var connectionConfig = {
host: "", // Hostname + ":" + port (no need for :port if 3360)
user: "", // User
password: "", // Password
database: "" // Schema
};
// PostgreSQL:
var connectionString = 'postgres://user:password#hostname:port';