Getting PROTOCOL_PACKETS_OUT_OF_ORDER in MySQL Node.js connection - mysql

I am an absolute newbie to Node.js. I am trying to create a MySQL database and connect it to a node.js server and build APIs.
Here's my db.config.js:
const mysql = require('mysql');
//local mysql db connection
const dbConn = mysql.createConnection({
host : '127.0.0.1',
user : 'root',
password : '',
database : 'node_mysql_crud_db'
});
dbConn.connect(function(err) {
if (err) throw err;
console.log("Database Connected!");
});
module.exports = dbConn;
And here's my server.js:
const express = require('express');
const bodyParser = require('body-parser');
// create express app
const app = express();
// Setup server port
const port = process.env.PORT || 3306;
// parse requests of content-type - application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }))
// parse requests of content-type - application/json
app.use(bodyParser.json())
// define a root route
app.get('/', (req, res) => {
res.send("Hello World");
});
// Require employee routes
const employeeRoutes = require('./src/routes/employee.routes')
// using as middleware
app.use('/api/v1/employees', employeeRoutes)
// listen for requests
app.listen(port, () => {
console.log(`Server is listening on port ${port}`);
});
When I run nodemon server, I get the following error:
/Users/mac/Flutter_Projects/NodeMysqlCrudApp/config/db.config.js:12
if (err) throw err;
^
Error: Packets out of order. Got: 80 Expected: 0
code: 'PROTOCOL_PACKETS_OUT_OF_ORDER',
fatal: true
I have added max_allowed_packet=500M in my.cnf file and yet I continue to receive the error.
How to resolve this issue?

Related

Getting "Cannot GET /isFavorite" on my Node.js app hosted on DigitalOcean

Why am I getting the following error? I have a small Nodejs app hosted on DigitalOcean. I am getting the following error "Cannot GET /isFavorite" when I run the following post command in Postman: "http://octopus-app-s7q5v.ondigitalocean.app:8080/isFavorite" with body JSON parameters of:
{
"userid": "101",
"petid": "1"
}
The route I have for the app is an app.post("/isFavorite") and not an app.get. It is connected to a MySQL database which is also hosted on DigitalOcean. I have included a small version of the code for the app below. Why would I be getting this error? When I add an app.get("/") and return a response of "Hello" that works. It runs locally. I have configured all the environment variables in DigitalOcean settings. I have the "ca-certificate.crt" in the root of my Nodejs app. DigitalOcean app platform says it builds and deploys fine on the server.
Also, regarding the console.logs I have added to the code, where are they stored? I can see the one which starts the webserver and listens but not any of the others. The app is listening on port 8080 and has an IP address of 0.0.0.0.
const bodyParser = require("body-parser");
const querystring = require('querystring');
const router = express.Router();
const app = express();
app.use("/", router);
const mysql = require('mysql');
const fs = require('fs');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(express.json());
app.post("/isFavorite", (req, res) => {
try {
console.debug("isFavorite Start");
const conn = mysql.createConnection({
host: process.env.DBHOST,
port: process.env.DBPORT,
user: process.env.DBUSER,
database: process.env.DBNAME,
password: process.env.DBPASSWORD
});
console.log("isFavorite logged on to db");
let selectQuery = 'SELECT COUNT(*) c FROM Favorites WHERE userID = ? AND petID = ?';
let query = mysql.format(selectQuery,[req.body.userid, req.body.petid]);
conn.query(query,(err, response, fields) => {
if(err) {
console.log(err);
res.status(500).send("Error querying database.");
return;
}
// rows added
console.log("isFavorite");
console.log(response.length);
if (response.length > 0) {
console.log(JSON.stringify(response));
res.status(200).json({IsFavorite: response[0].c >= 1});
} else {
res.status(200).json({IsFavorite: false});
}
});
} catch (err) {
next(err);
}
});
let PORT = process.env.PORT || 3000;
let IP = process.env.IP || '127.0.0.1';
app.listen(PORT, IP, () => {
console.log('Server is running at port ' + PORT + ' and IP = ' + IP);
});

How do I resolve this error of postman which is unable to send request?

Hii I am connecting Mysql Workbench and Nodejs to which the connection is successful. After the connection I have made a single get request which to me seems correct but I am still getting an error in the Postman! Can anyone help me?Here is my code-
const express = require('express')
const app = express();
var mysql = require('mysql')
var bodyParser = require('body-parser')
// db connection ----
var con = mysql.createConnection({
host:'localhost',
user:'root',
database:'tutorial',
password:'root'
})
con.connect(function(err){
if(err){
console.log("Error connecting to db");
}
else{
console.log("Connection established ");
}
})
const port = 8080;
app.listen(()=>{
console.log("Server started at port",port)
})
app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json());
app.get('/customer/' , (req, res) => {
con.query('SELECT * FROM customer', (err, rows, fields) => {
if (!err)
res.send(rows);
else
console.log(err);
})
} );
module.exports = { app }
And this is the error I am getting in postman-
This is the console for vs code-
This is the console of postman-
You did not set the port in listen
app.listen(port, ()=>{
console.log("Server started at port",port)
})
Have you explicitly set the port to 8080 somewhere else? Express generator creates a www file in the bin folder, where your can set the port.
var port = normalizePort(process.env.PORT || '8080');
app.set('port', port);
You can also set the port in listen
app.listen(port, () => {
console.log("Server started at port", port);
});

React.js + Express: how to run SQL requests implying several databases?

I am currently working on the API of a React.js project. I have no trouble running SQL requests with databases on MySql servers using Express as long as the SQL request only implies a single database.
My problem: I now have to run an SQL request which implies using data from several databases and I do not know how to do it.
What I currently do in my server.js file to run SQL on a single database:
...
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const mysql = require('mysql');
...
let sql = "";
...
// *************************
// CLIENT & DB CONFIGURATION
// *************************
const app = express();
app.use(bodyParser.json()); // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true
}));
var server = app.listen(3001, "127.0.0.1", function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
});
app.use(cors());
const connection = mysql.createConnection({
host : 'myhost.fr',
user : 'someone',
password : 'aZefdt%',
database : 'SuiviTruc',
multipleStatements : true
});
connection.connect(function(err) {
if (err) throw err
console.log('You are now connected with SuiviTruc database...')
});
// **************
// Request sample
// **************
app.get('/SelectAffaire_',(req, res) => {
let sql=`SELECT * FROM t_Affaire_;`
connection.query(sql, (error, result)=> {
if (error) throw error;
res.send(result);
})
})
Thanks for your help!

Express taking forever to load mySQL query?

I'm trying to query a single line from a 28k record database as a test but it isn't going through but when I load up 'localhost:3001/api/get' it stays loading, even though my connection says success? Is it actually even connecting to the db?
my data bases schema is:
id | state_name | city
const bodyParser = require('body-parser');
const express = require('express');
const app = express();
const mysql = require('mysql');
const cors = require('cors');
const db = mysql.createPool({
host: "localhost",
user: "root",
password: "password",
database: "states_city"
});
app.use(cors());
app.use(express.json());
app.use(bodyParser.urlencoded({extended:true}));
app.get('/api/get', (req, res)=>{
const sqlGet = "SELECT city FROM state_city city = 'Chicago'";
db.query(sqlGet, (err, res)=>{
console.log("success");
});
});
app.listen(3001, ()=>{
console.log("running on port 3001");
});
First you must make server running. Remove that API route you had set before running server.
app.listen(3001, ()=>{
console.log("running on port 3001");
});
Now you must create database connection. Create new file dbconn.js
var mysql = require('mysql');
const db = mysql.createPool({
host: "localhost",
user: "root",
password: "password",
database: "states_city"
});
Now create new connection:
var new_connection = mysql.createPool(
db
);
new_connection.on('connection', function (connection) {
console.log('DB Connection established');
connection.on('error', function (err) {
console.error(new Date(), 'MySQL error', err.code);
});
connection.on('close', function (err) {
console.error(new Date(), 'MySQL close', err);
});
});
// export connection
module.exports = new_connection;
Include that connection in other file:
var db_connection = require('../dbconn');
db_connection.query(query, params, function (error, results, fields) {
//Do your query
});
Read about project structure to make your code easy to edit.

Can't connect to mysql using node express

I'm trying to connect to mysql using express but I cannot get it to work. I've searched similar questions but couldn't find the correct one for me. Right know I have this simple code:
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var mysql = require('mysql');
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: ''
});
connection.connect((err) => {
if(err) {
console.log(err);
} else {
console.log("Connected");
}
});
var authRouter = require('./routes/login');
var homeRouter = require('./routes/home');
var app = express();
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.set('view engine', 'ejs');
app.use('/', authRouter);
app.use('/', homeRouter);
app.listen(3000, () => {
console.log("Running on port 3000");
})
I simply installed mysql using npm and tried to run the code. I keep getting Error: Connection lost: The server closed the connection.
It doesn't even log the error on const connection = mysql.createConnection
Tried using XAMPP but I get the same error.
Any help would be really appreciated, thanks!